Search code examples
angularcontrolvalueaccessor

Using formcontrol.setError() to propagate error to a custom control component


I am have created a custom form control component using the controlValueAccesor interface provided by Angular.

Now I am using that custom component like this.

Parent:

<custom-control [formControl]="customControl"></custom-control>

it is working fine and as expected. The issue comes when I try to run setErrors method, since I want the error to propagate to the custom component so I can show error sent from outside of the component.

In the parent component that is using custom-control when I do this:

someValidation() {
  this.customControl.setErrors({
    myError: true
  })
}

Inside the template of my custom control component, I can see this

<form [formGroup]="form">
  <div> {{form.errors}} </div> <!-- I want to be able to propage 'myError' here -->
</form>

any suggestions?


Solution

  • I think you can inject the current FormControl instance in your custom-component(which implements ControlValueAccessor) like this:

    // inside `custom-component`
    
    get errors () {
      return this.ctrl.errors;
    }
    
    constructor (private ctrl: NgControl) { }
    

    This solution is based on how FormControl directive is implemented:

    constructor(
          /* ... validators ... */
          @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
          /* ... */) {
        super();
        this._rawValidators = validators || [];
        this._rawAsyncValidators = asyncValidators || [];
        this.valueAccessor = selectValueAccessor(this, valueAccessors);
      }
    

    If you'd like to read more about Angular Forms,I'd recommend checking out A thorough exploration of Angular Forms.