在angular2中动态创建多个表单

Dynamically create multiple forms in angular2

我正在从数据库中获取一些数据,并根据结果数量创建表单。例如。如果我得到总共 3 行,其中列为 name,age 和 class 。然后我需要创建三个表单元素,名称、年龄和 class 作为表单元素。提前致谢

您可以使用 FormArray 创建多个表单组。

使用 FormBuilder,我们可以为 FormControl 创建一个 FormGroup。在 FormGroup 中定义一个变量作为 FormArray 并动态地将 FormControls 添加到该数组。

public dataForm = FormGroup;
const dbData = // data from database eg. [{name:x, age: 8, class: A},..]
...
constructor(
    private _fb: FormBuilder
) {}
...
ngOnInit() {
    this.dataForm = this._fb.group({
       subFormList: this._fb.array([])
    });
    this.getValues();
}
getValues() {
   const control = <FormArray> this.dataForm.get('subFormList');
   for (row of this.dbData) {
      const temp = this._fb.group({
         name: [row['name']],
         age: [row['age']],
         class: [row['class']]
      });
      control.push(temp);
   }
}

希望对您有所帮助。