如何将新表单控件添加到嵌套表单组?

时间:2017-06-11 21:45:37

标签: angular angular2-forms angular-reactive-forms

我有这个表单组:

this.form = fb.group({
  'teacher': [''],
  'schools': fb.array([
    fb.group({
      'school_name': [''],
      'school_description': [''],
    })
  }) 
});

问题是:

如何将新的表单控件(名为school_city)添加到特定的*组" FormArray以编程方式通过函数?

1 个答案:

答案 0 :(得分:6)

要为FormArray中的每个组添加一些控件,您可以执行以下操作:

someFunc() {
  const formArr = this.form.get('schools') as FormArray;

  for (const group of formArr.controls) {
    group.addControl('school_city', this.fb.control(''));
  }
}

PLUNKER

修改#1

由于OP现在解释他想将control添加到特定组:

您必须传递要添加control的组的索引:

someFunc(idx: number) {
  const group = this.form.get(`schools.${idx}`) as FormGroup;

  group.addControl('school_city', this.fb.control(''));
}