我的角反应形式低于误差。我有什么想念的吗?我在第二种嵌套形式中遇到错误。
error TS7053: Element implicitly has an 'any' type because expression of type '"controls"' can't be used to index type 'AbstractControl<any, any>'.
Property 'controls' does not exist on type 'AbstractControl<any, any>'.
19 <tr *ngFor="let data of item.get('rows')['controls']; let j = index" formGroupName="j">
TS文件
public usersForm!: FormGroup;
constructor() { }
ngOnInit() :void {
this.usersForm = new FormGroup({
users: new FormArray([
new FormGroup({
key: new FormControl(),
rows: new FormArray([
new FormGroup({
updatedBy: new FormControl(this.formatFormValue('')),
updatedAt: new FormControl(this.formatFormValue('')),
comment: new FormControl(this.formatFormValue('')),
}),
]),
}),
]),
});
}
getFormControl() {
return this.usersForm .get('users') as FormArray;
}
模板文件
<form [formGroup]="usersForm ">
<div formArrayName="users">
<table *ngFor="let item of getFormControl().controls; let i = index" [class.table_margin]="i>0">
<div formGroupName="i">
<tr>
<th>{{item.get('key').value}}</th>
</tr>
<span formArrayName="rows">
<tr *ngFor="let data of item.get('rows')['controls']; let j = index" formGroupName="j">
<td >
<input type="text" formControlName="comment">
</td>
</tr>
</span>
</div>
</table>
</div>
</form>
我也尝试过 item.get('rows').controls,但效果不佳。
修复错误的一种方法是为组件中的“行”定义一个 getter:
getFormControl() {
return this.usersForm .get('users') as FormArray<FormGroup>;
}
get rows() {
return this.getFormControl().controls['rows'] as FormArray<FormGroup>;
}
然后在迭代行时在 html 模板中使用它:
<span formArrayName="rows">
<ng-container *ngFor="let data of rows.controls; let index = index">
<ng-container [formGroupName]="index">
<td >
<input type="text" formControlName="comment">
</td>
</ng-container>
</ng-container>
</span>
或者您可以简单地在模板中进行类型转换:
<span formArrayName="rows">
<ng-container *ngFor="let data of (item.get('rows') as FormArray<FormGroup>).controls; let index = index">
<ng-container [formGroupName]="index">
<td >
<input type="text" formControlName="comment">
</td>
</ng-container>
</ng-container>
</span>
基本上,据我所知,错误状态(我是 Angular 的新手,所以请大发慈悲)指出该元素没有定义的类型,您可以迭代(您正在尝试访问 AbstractControl 的索引“控件”,它没有'不存在)因此“任何”你正在尝试访问 AbstractControl 的索引'控件'(https://angular.io/api/forms/AbstractControl)。 所以你需要指定你正在迭代一个 FormArray。
这是 FormArray 上的角度指南:https://blog.angular-university.io/angular-form-array/