我有一个包含 3 个 FormGroup 的 FormArray,每个表单组有 2 个控件。我不确定如何访问表单组中的控件来设置表单控件名称。
设置表格
this.form = this.formBuilder.group({
---a couple controls---
properties: this.formBuilder.array({
first: this.formBuilder.group({
label: new UntypedFormControl(),
value: new UntypedFormControl(),
}),
second: this.formBuilder.group({
label: new UntypedFormControl(),
value: new UntypedFormControl(),
}),
third: this.formBuilder.group({
label: new UntypedFormControl(),
value: new UntypedFormControl(),
}),
})
})
数组属性的 getter
get properties() {
return this.form.controls.properties as FormArray;
}
我能够添加和删除一行属性。
html 为表单。我不确定如何从表单数组访问每个表单组中的标签和值控件。
<div formArrayName="properties">
<ng-container *ngFor="let propertiesForm of properties.controls; let i = index">
<div [formGroupName]="i">
---then I have 3 sets of mat form fields each with and label and value---
</div>
</ng-container>
</div>
this.formBuilder.array()
方法只接受一个数组参数。您无法为其提供对象。
方法 1:使用
this.formBuilder.array([])
properties
结构修改为数组。FormGroup
properties
中添加所需的 FormArray
数量。您应该考虑实现一个函数来生成单个属性FormGroup
。这样做的目的是减少代码冗余。ngOnInit() {
// Form with Form Array
this.form = this.formBuilder.group({
//---a couple controls---
properties: this.formBuilder.array([]),
});
for (let i = 0; i < 3; i++)
this.properties.push(this.createPropertyFormGroup());
}
createPropertyFormGroup() {
return this.formBuilder.group({
label: new UntypedFormControl(),
value: new UntypedFormControl(),
});
}
<form [formGroup]="form">
<div formArrayName="properties">
<ng-container
*ngFor="let propertiesForm of properties.controls; let i = index"
>
<div [formGroupName]="i">
<label>Label: </label>
<input formControlName="label" />
<br />
<label>Value: </label>
<input formControlName="value" />
</div>
<hr />
</ng-container>
</div>
</form>
方法 2:使用
this.formBuilder.group({})
KeyValuePipe
来迭代属性 FormGroup
对象并生成每个 FormGroup
。this.form = this.formBuilder.group({
//---a couple controls---
properties: this.formBuilder.group({
first: this.createPropertyFormGroup(),
second: this.createPropertyFormGroup(),
third: this.createPropertyFormGroup(),
}),
});
<form [formGroup]="form">
<div formGroupName="properties">
<ng-container
*ngFor="let propertiesForm of propertiesFormGroup.controls | keyvalue;"
>
<div [formGroupName]="propertiesForm.key">
<label>Label: </label>
<input formControlName="label" />
<br />
<label>Value: </label>
<input formControlName="value" />
</div>
<hr />
</ng-container>
</div>
</form>