Angular 不会更新 FormArray 中的值



我正在尝试填充一个表单组,该组包含一个具有动态长度的表单数组。具有多个选择的下拉列表确定创建了多少个数组。每个创建的数组都有新的下拉列表。但只有最后一个下拉列表的值会添加到表单中。

我正在使用Angular 11.0.5

我用这个作为参考,但它对我来说没有产生相同的输出

我的表单

this.form = this.fb.group({
parents: [[]],
children: this.fb.array([])
});

如何在parents中更改值的children中创建数组

get formChildren(): FormArray {
return this.form.get('children') as FormArray;
}
addArrays(number){
this.formChildren.clear();
Array<Datatype>(number).fill(null).map(() => this.formChildren.push(this.fb.control([])));
}

我的HTML看起来像这个

<form [formGroup]="metaDataChangeFormGroup">
<mat-form-field>
<mat-select [multiple]="true" formControlName="parents">
<mat-option *ngFor="let parent of parents [value]="parent">
{{ parent }}
</mat-option>
</mat-select>
</mat-form-field>
<ng-container formArrayName="children">
<mat-form-field *ngFor="let parent of formParents.value; let i = index">
<mat-select
[multiple]="true"
[placeholder]="i.toString()"
[formControlName]="i">
<ng-container *ngFor="let child of childrenFacade.select()>
<mat-option *ngIf="child && child.parent.id == parent.id"
[value]="child">
{{ child }}
</mat-option>
</ng-container>
</mat-select>
</mat-form-field>
</ng-container>
</form>

到目前为止,这种方法可以将最后一个选定父项的子项的下拉列表保存在正确的数组中,但其他下拉列表则无法保存。当我在formChildren上订阅valuesChanged时,它会在我创建控制台日志时被触发,但表单中的数组保持为空。完整的表格打印在我的组件上。为什么它对最后一位家长有效,而对其他家长无效?谢谢你的帮助!

您希望您的表单看起来像这样:

this.form = this.fb.array([
this.fb.group({
parent: []
children: this.fb.array([])
}),
this.fb.group({
parent: []
children: this.fb.array([])
}),
]);

使用此功能,您可以为每个父级的每个子级维护表单控件。我只是添加了两个家长作为例子。当然,在您的代码中,您需要动态生成FormGroup

这是你修改后的StackBlitz来展示你的行为。

最新更新