angularformgroupscontrolvalueaccessor

angular validation state of a nested ControlValueAccessor is not correctly propagated in parents, how to implement this validation?


I have an issue in an angular 10 app, with the propagation of the state of a formGroup to its parent, at initialization.

Issue: at component initialization, the validation state of a sub-form is not correctly propagated in parents of more than one level.

More precisely, I have 3 nested components. All of them are forms and both children implement ControlValueAccessor. They communicate by "formControlName" attribute. The deepest form is initialized in error (a required field). The parent does not receive the validity status (it remains valid).

Here is a reproduction of the problem:

https://stackblitz.com/edit/ngx-sub-form-hzo8wj?file=src/app/app.component.ts

I want "base formgroup" to be invalid on initialization. The validity of "level 2" should be propagated in "level 1" THEN "level 1" in "base formgroup".

It probably comes from the normal angular cycle.

I found a hack while waiting for a better solution:

  public ngAfterViewInit(): void {
    this._injector.get(NgControl).control.updateValueAndValidity();
  }

We manually restart the validation of the parent from the child after the first angular cycle. And this is cascaded in all the sub-components.

How could I avoid to use this hack ?


Solution

  • Your parent form is valid, because it doesn't know about nested controls, as each instance of AbstractSubformComponent will create it's own formGroup.
    One way to fix it is to add child controls dynamically to parent form group.
    Here is your stackblitz with changes