Home > front end >  How to get nested group controls in reactive forms
How to get nested group controls in reactive forms

Time:04-01

I am getting an error, while i retrieve the nested formgroup from the main formgroup.

here is the error:

Type 'AbstractControl[]' is not assignable to type '{ [key: string]: AbstractControl; }'.
  Index signature for type 'string' is missing in type 'AbstractControl[]'

my code:

 get form(): { [key: string]: AbstractControl } {
    return this.patientForm.controls;//works
  }

  formChild(group: string): { [key: string]: AbstractControl } {
    const childControls = (this.patientForm.get(group) as FormArray).controls;
    return childControls; //throws above error. 
  }

any one help me to sort this issue? using get operator, is it possible to get child group from the main form group? thanks in advance.

CodePudding user response:

FormArray contains array of AbstractControls.

If you want to get a key map of AbstractControls you should expect FormGroup returned from the getter:

formChild(group: string): { [key: string]: AbstractControl } {
  const childControls = (this.patientForm.get(group) as FormGroup).controls;
                                                       ^^^^^^^^^^
  return childControls; //throws above error. 
}
  • Related