angulartypescriptvalidationcontrolvalueaccessor

Angular passing FormControl Validators to Child Component


I have two Angular Components.

parent.ts and child.ts

Parten.ts has a Form group and child.ts is passing the Form date via CVA to the parent.

Now I want to build an reusable child component to be able to generate child1.ts, child2.ts, …

This works totaly fine until now and I habe build multiple components like this.

Now I have the issue that some of the child components are required and some aren’t.

If I supply the Validators in the Parent component the Validation works and the Form is invalid if the fields are empty but the Child component itself does not get the Validation state passed from the parent.ts and so stays valid.

This results in the child not showing the the ng-error message.

How can I pass the Validation state from the parent to the child to show the error messages?


Solution

  • Provide your CVA like so :

    
    constructor(
      @Optional() @Self() private ngControl: NgControl
    ) {
      if (this.ngControl) this.ngControl.valueAccessor = this;
    }
    
    

    And remove the providers from your @Component decorator.

    If you do that, you get access to

    this.ngControl.control.valid
    this.ngControl.control.invalid
    this.ngControl.control.pending
    this.ngControl.control.status
    

    Which should give you the state of your CVA at all times.