【发布时间】:2021-11-13 06:17:42
【问题描述】:
我正在尝试使用 FormArray 动态控制 FormGroup 的数量,以便设置 FormArray 长度。
myForm = this.fb.group({
formGroupsToAdd: ['5'],
formList: this.fb.array(this.getFormControls(5))
});
getFormControls(numberOfFormGroups: number) {
const myArray = new Array(numberOfFormGroups);
myArray.fill(this.fb.group({
length: [''],
width: [''],
height: ['']
}));
return myArray;
}
我也有办法得到这个formList: FormArray
get unitList() {
return this.myForm.get('formList') as FormArray;
}
但是,当我在此 FormArray 中向单个控件添加值时,它会更新 FormArray 中的所有 FormGroups。
<div formArrayName="formList">
<div *ngFor="let unitForm of formList.controls; let i = index">
<div [formGroup]="formList.controls[i]">
<pre>{{formList.controls[i].value | json}}</pre>
<pre>i = {{i}}</pre>
<mat-form-field>
<input matInput formControlName="length" />
</mat-form-field>
<mat-form-field>
<input matInput formControlName="width" />
</mat-form-field>
<mat-form-field>
<input matInput formControlName="height" />
</mat-form-field>
</div>
</div>
</div>
所以我的formList.value 看起来像这样......
[
{
"length": "",
"width": "asdf",
"height": ""
},
{
"length": "",
"width": "asdf",
"height": ""
},
{
"length": "",
"width": "asdf",
"height": ""
},
{
"length": "",
"width": "asdf",
"height": ""
},
{
"length": "",
"width": "asdf",
"height": ""
}
]
相反,我需要一个 FormGroup 来包含它自己独特的 FormControl 值。
我做错了什么?为什么 [formGroup]="formList.controls[i]" 不能通过为每个 formGroup 提供唯一标识符来满足我的需求?
编辑:我添加了一个堆栈闪电战来解决我的问题。
https://stackblitz.com/edit/angular-ivy-sa7pbb?file=src/app/app.component.html
【问题讨论】:
标签: angular angular-reactive-forms formarray formgroups