[英]Angular reactive forms: unnamed FormArray inside FormArray
I'm confused about how to display a proper input table for my type of data (or is the way I construct FromGroup even valid), so I here is my component我对如何为我的数据类型显示正确的输入表感到困惑(或者我构造 FromGroup 的方式是否有效),所以我在这里是我的组件
export class FoiFormComponent {
listForm = new FormGroup({
fois: new FormArray([
new FormArray([
new FormControl('01-01-2021'),
new FormControl('101'),
new FormControl('201')]),
new FormArray([
new FormControl('02-01-2021'),
new FormControl('102'),
new FormControl('202')])
])
});
constructor() {}
getFois(): FormArray[] {
return (this.listForm.get('fois') as FormArray).controls as FormArray[];
}
}
The result that I want should look something like我想要的结果应该类似于
I tried to do this我试着这样做
<table>
<tr *ngFor="let foiArr of getFois; index as i" [formGroupName]="i">
<td *ngFor="let row of foiArr.controls[i].controls; index as j">
<input formControlName="j">
</td>
</tr>
</table>
But the error that I get is 'NgFor only supports binding to Iterables such as Arrays.'但我得到的错误是“NgFor 仅支持绑定到诸如 Arrays 之类的 Iterables。” (Even though it is array, and in code I can do this console.log(this.getFois()[0]);
(即使它是数组,并且在代码中我可以执行此操作console.log(this.getFois()[0]);
Note: so the table is dynamic both in columns and rows, and that is why I don't have a name for each of the arrays or formGroups.注意:所以表格在列和行中都是动态的,这就是为什么我没有为每个 arrays 或 formGroups 命名的原因。 Any help or hints are greatly appreciated.非常感谢任何帮助或提示。
In case anyone is interested I was able to do it by using indexes as FormArrayName:如果有人感兴趣,我可以通过使用索引作为 FormArrayName 来做到这一点:
<form [formGroup]="fois">
<table>
<ng-container *ngFor="let control of getFoiControls(); let i = index">
<tr [formArrayName]="i">
<td *ngFor="let row of getDay('' + i).controls; let j = index">
<input [formControlName]="j">
</td>
</tr>
</ng-container>
</table>
</form>
And in the component:在组件中:
fois = new FormGroup({});
constructor() {}
getDay(day: string): FormArray {
return this.fois.get(day) as FormArray;
}
getFoiControls(): string[]{
return Object.keys(this.fois.controls);
}
ngOnInit(): void {
this.fois.addControl('0', new FormArray([
new FormControl('01-01-2021'),
new FormControl('101'),
new FormControl('201')
]));
this.fois.addControl('1', new FormArray([
new FormControl('02-01-2021'),
new FormControl('102'),
new FormControl('202')
]));
this.fois.addControl('2', new FormArray([
new FormControl('02-01-2021'),
new FormControl('103'),
new FormControl('203')
]));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.