Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 591
anonymous Avatar asked Jun 11 '17 21:06

anonymous


Video Answer


1 Answers

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(''));
}
like image 87
developer033 Avatar answered Sep 19 '22 21:09

developer033