anonymous
anonymous

Reputation: 1691

How can I add a new form control to the nested form group?

I have this form group:

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

The question is:

How can I add a new form control (named school_city) to a specific *group" of FormArray programatically through a function?

Upvotes: 10

Views: 9214

Answers (1)

developer033
developer033

Reputation: 24874

To add some control to every group inside FormArray, you can do the following:

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

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

PLUNKER

Edit#1:

As the OP now explains that he wants to add the control to a specific group:

You have to pass the index of the group that you want to add the control:

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

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

Upvotes: 20

Related Questions