The entered form control nested FormArray in the FormGroup control

I have a group of forms, for example:

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 to get information about events of a nested array?

 const control = (<FormArray>this.form.controls['schools']).controls[0]['events']; 
+5
source share
3 answers

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

 this.form.get('schools') 

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

 this.schools.at(0) 

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

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

Here is a working plnkr example.

+5
source

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 objects, you can use this:

  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); 
+1
source

If you want to change the value of the nested FormArray, this works for me:

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

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

0
source

Source: https://habr.com/ru/post/1262529/


All Articles