Cannot bind custom FormGroup(via ControlValueAccessor) inside FormArray

69 Views Asked by At

We have a 2 components. Lets call them parent and child and both of them implements ControlValueAccessor.

Parent form is:

this.formBuilder.group({
    children: this.formBuilder.array([])
})

Child form is:

this.formBuilder.group({
    childProp1: this.formBuilder.array([]),
    childProp2: this.formBuilder.array([]),
})

Please note that, child form has own function like "add1", "add2", "remove1" etc to manipulate its properties.

Also mind the all ControlValueAccessor methods are implemented, and the all other cases with reusable forms works like a charm. Just interested may be someone already faced this type of issue and can help.

In parent component template

<div [formGroup]="form">
    <div
        formArrayName="children"
    >
         <div
             *ngFor="let control of form.controls.children['controls']; let controlIndex = index"
        >
            <app-child
                [formGroup]="control"
            ></app-child>
        </div>
    </div>
</div>

The problems is that all manipulations inside child component like a add, remove does not affect the parent form. No any exceptions in a console. Binding works if will be passed any property name of form (just for testing) to formControlName outside of formArray. Issue occurs only inside formArray.

Looks like so bad formulated, structured question, sorry for that.

1

There are 1 best solutions below

1
On

You have not a formArray of FormGroup else a FormArray of FormControls. Yes, the formControls store objects, but they are FormControls

Always you use a FormArray is better use a getter of the formArray

get childrenArray()
{
   return this.form.get('children') as FormArray
}

<div [formGroup]="form">
    <div formArrayName="children">
         <div *ngFor="let control of childrenArray.controls; let controlIndex = index">
            <app-child
                [formControlName]="controlIndex"
            ></app-child>
        </div>
    </div>
</div>

NOTE: I imagine you use a very old angular version, and you can also use [formControl]="control" but I think remember this way is related to Angular 5 or below (in greater versions you can not use the "variable" of the loop to refered to the formGroup or the formControl).