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'];
The FormArray is a way to Manage collection of Form controls in Angular. The controls can be FormGroup, FormControl, or another FormArray. Because it is implemented as Array, it makes it easier dynamically add controls.
With a parent FormGroup, the name input needs the syntax formControlName=name in order to be associated with the correct FormControl in the class. This syntax tells Angular to look for the parent FormGroup, in this case heroForm, and then inside that group to look for a FormControl called name.
We do not have a name to the FormGroup . The Index of the element is automatically assigned as the name for the element. Hence we use the [formGroupName]="i" where i is the index of the FormArray to bind the FormGroup to the div element. Finally, we add the controls using the formControlName directive.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With