angularangular-reactive-formsformarrayformgroupsangular-dynamic-forms

How to bind a formarray of form groups from parent to child component in Angular?


Need help from anyone who has worked on angular reactive forms. I have a parent component and 3 child components

In the parent component, I have a form which looks like this :

parent form : 

formarray1 : formarray[5 formgroups]
formarray2 : formarray[5 formgroups]
formarray3 : formarray[5 formgroups]

Parent component pseudocode:

<form [formGroup] = "parentform">
      @for(i for index){ //loop runs 5 times
          <app-child1></app-child1> // bind array1
          <app-child2></app-child2> // bind array2
          <app-child3></app-child3> // bind array3
       }
</form>

In the child component, there are form controls and validations done for the specific Formgroup.

How should I bind the 3 formarrays to the 3 child components in such a way that for every loop run, the "i"th formgroup in the formarray is bound with the "i"th child component rendered in the parent component?


Solution

  • You can either just pass it in as an input. Make sure to not call it "formGroup" though or your child components implement the FormControlValueAccessor than you can use the [formGroup] binding from ReactiveFormsModule.

    But just for a child view I would go with the first option

    <form [formGroup] = "parentform">
          @for(i for index){ //loop runs 5 times
              <app-child1 [_formGroup]="parentform.controls[i].formarray1"></app-child1> // bind array1
              <app-child2 [_formGroup]="parentform.controls[i].formarray2"></app-child2> // bind array2
              <app-child3 [_formGroup]="parentform.controls[i].formarray3"></app-child3> // bind array3
           }
    </form>