In order to create a reactive forms, a parent FormGroup
is a must. This FormGroup
can further contain formControls
, child formGroups
or formArray
FormArray
can further contain array of formControls
or a formGroup
itself.
When should we use formArray?
Please read this beautiful post which explains the usage of formArray
The interesting example in that blog is about the trips formGroup
The structure of trips formGroup
using formControl
and formArray
would look something like:
this.tripForm = this.fb.group({
name: [name, Validators.required],
cities: new FormArray(
[0] ---> new FormGroup({
name: new FormControl('', Validators.required),
places: new FormArray(
[0]--> new FormGroup({
name: new FormControl('', Validators.required),
}),
[1]--> new FormGroup({
name: new FormControl('', Validators.required),
})
)
}),
[1] ---> new FormGroup({
name: new FormControl('', Validators.required),
places: new FormArray(
[0]--> new FormGroup({
name: new FormControl('', Validators.required),
}),
[1]--> new FormGroup({
name: new FormControl('', Validators.required),
})
)
}))
})
Do not forget to play with this DEMO, and notice the usage of array for cities
and places
of a trip.