要将数据对象与Angular响应式表单中的FormArray绑定在一起,可以按照以下步骤进行操作:
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
export class YourComponent {
form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
yourFormArray: this.formBuilder.array([])
});
}
}
export class YourComponent {
form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
yourFormArray: this.formBuilder.array([])
});
}
bindDataToFormArray(data: any[]) {
const formArray = this.form.get('yourFormArray') as FormArray;
// 清空FormArray中的控件
formArray.clear();
// 遍历数据对象数组,并为每个对象创建一个FormGroup,并将其添加到FormArray中
data.forEach((item: any) => {
const formGroup = this.formBuilder.group({
// 在这里定义与数据对象属性对应的FormControl
propertyName: [item.propertyName]
});
formArray.push(formGroup);
});
}
}
bindDataToFormArray
方法,将数据对象与FormArray绑定在一起:export class YourComponent {
// ...
ngOnInit() {
const data = [{ propertyName: 'Value 1' }, { propertyName: 'Value 2' }];
this.bindDataToFormArray(data);
}
}
通过以上步骤,你可以将数据对象与FormArray的每个对象绑定在一起,实现响应式表单的功能。