edumas000
edumas000

Reputation: 282

Model Driven Form Nested FormArray Control in a FormGroup control

I have a form group like so:

 this.form = fb.group({
  'teacher': [''],
  'schools': fb.array([
      fb.group({
        'school_name': [''],
        'school_description': [''],
        'events': fb.array([
          fb.group({
            'event_name': ['']
          })
        ])
      })
  ])
});
const control = (<FormArray>this.form.controls['schools']).controls[0]['events'];

How do I get the nested array control 'events'?

const control = (<FormArray>this.form.controls['schools']).controls[0]['events'];

Upvotes: 5

Views: 3370

Answers (3)

Iulian Cristea
Iulian Cristea

Reputation: 11

In case you want to change a value for a nested FormArray, for me this works:

(<FormArray>this.formModel.controls['schools']).at(el).patchValue({school_name:'your new value'});

el is the index element for which one you want to apply the patch value.

Upvotes: 0

stealththeninja
stealththeninja

Reputation: 3791

I recommend having a look at the Angular 2 examples for nested form array and nested form group for a look at how to build complex forms. With FormGroup, you can use .get(name: string) to retrieve a control. This example gets the schools FormArray control:

this.form.get('schools')

For FormArray, you can retrieve a control from the array using .at(index: number). This example gets the first FormGroup control in the array:

this.schools.at(0)

To put it all together, there are nicer (read: more reusable, more readable) ways to express this but this chain will get you the first event from your first school:

this.form.get('schools').at(0).get('events')

Here's a working plnkr example.

Upvotes: 5

Saeed
Saeed

Reputation: 3775

You should use this code:

      let listForm: any;
      var subFormGroup = new FormGroup({});
        subFormGroup.addControl("Your Controll Name", new FormControl('',res["Required"] ? Validators.required : null))

      listForm = this.builder.array([
        subFormGroup
      ]);
      this.form.addControl("Your new ArrayControll Name", listForm);

When you have an Array of Object,you can use that:

 let listForm: any;
 var controlItems =[Your Object Array];
 var subFormGroup = new FormGroup({});
 Object.keys(controlItems).forEach(function(key){
    subFormGroup.addControl(controlItems[key], new FormControl('',res["Required"] ? Validators.required : null))
  })
 listForm = this.builder.array([
     subFormGroup
 ]);
 this.form.addControl("Your new ArrayControll Name", listForm);

Upvotes: 1

Related Questions