I need to set a value in a nested control in a FormBuiler and the model is the following:
this.addAccForm = this.fb.group({
accid: [\'\', Validators.re
Define a FormGroup
to hold a form.
addAccForm: FormGroup
Create a form using FormBuilder
.
this.addAccForm = this.fb.group({
accid: ['', Validators.required],
status: '',
cyc: this.fb.array([])
})
Now create a method to patch the form values. You may pass the model as parameters to the method. Or a variable defined in the component class.
// GETER TO RETRIEVE THE CYC FORMARRAY
get cycFormArray(): FormArray {
return this.addAccForm.get('cyc') as FormArray;
}
patchForm(model: any) {
this.addAccForm.patchValue({
accid: [model.accid, Validators.required],
status: model.status,
});
// PASS ARRAY TO PATCH FORM ARRAY
this.patchCyc(model.cyc);
}
// METHOD TO PATCH FORM ARRAY
patchCyc(cycArray: any[]) {
cycArray.forEach(item => {
this.cycFormArray.push({
this.fb.group({
prop1: item.prop1,
prop2: item.prop2,
...
})
})
})
}
The patchCyc()
method will loop through the array passed as parameter. A new FormGroup
will be pushed to the cyc FormArray
in each loop.