【发布时间】:2020-07-22 16:30:12
【问题描述】:
这是我尝试使用硬编码数据源并正常工作的方法。但在从 api 获取数据时抛出类似“ERROR TypeError: Cannot read property 'foreach' of undefined”和“ERROR Error: Cannot find control with path: 'users -> 0'”之类的错误。
ngOnInit() {
this.empService.getEmployees().subscribe((res: any[]) => {
this.dataSource = new MatTableDataSource(res);
});
this.tableForm = this.formBuilder.group({
users: this.formBuilder.array([]),
});
console.log(this.dataSource);
this.setUsersForm();
this.tableForm.get("users").valueChanges.subscribe((users) => {
console.log("users", users);
});
}
private setUsersForm() {
const userCtrl = this.tableForm.get("users") as FormArray;
console.log(this.dataSource);
this.dataSource.foreach((user) => {
console.log(user);
userCtrl.push(this.setUsersFormArray(user));
});
}
private setUsersFormArray(user) {
return this.formBuilder.group({
employee_name: [user.employee_name],
location: [user.location],
});
}
<form [formGroup]="tableForm">
<mat-table formArrayName="users" [dataSource]="dataSource">
<ng-container matColumnDef="EmployeeName">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell
*matCellDef="let row let rowIndex = index"
[formGroupName]="rowIndex"
>
<input type="text" size="2" formControlName="employee_name" />
</mat-cell>
</ng-container>
<ng-container matColumnDef="Location">
<mat-header-cell *matHeaderCellDef>Location </mat-header-cell>
<mat-cell
*matCellDef="let row let rowIndex = index"
[formGroupName]="rowIndex"
>
<input type="text" size="7" formControlName="location" />
</mat-cell>
</ng-container>
<!-- Header and Row Declarations -->
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</form>
【问题讨论】:
-
由于 API 调用是异步的,您需要在订阅中移动动态表单创建。
-
对不起,我没有得到你。你的意思是表单构建器组应该在订阅中?
-
移动 this.setUsersForm();内订阅。
-
是的,我也试过了..但错误仍然存在。数据源未定义。
标签: angular angular-material angular-reactive-forms form-control