Search code examples
angularformsangular6angular-material-6

Angular6 Material custom form field control with validation errors (mat-error)


How to make a Material custom form field control (like this one) to support form validation and display them with mat-error? I understand that the regular matInput directive uses ErrorStateMatcher (doc) but I don't understand how I can link it with a custom form field.


Solution

  • By looking at some existing component from Material2 (https://github.com/angular/components/blob/master/src/material/select/select.ts), I found a solution. I created a base class following this example

    export const _MatSelectMixinBase:
    CanDisableCtor &
    HasTabIndexCtor &
    CanDisableRippleCtor &
    CanUpdateErrorStateCtor &
    typeof MatSelectBase =
        mixinDisableRipple(mixinTabIndex(mixinDisabled(mixinErrorState(MatSelectBase))));
    

    I had to copy from the Material repo some types like CanUpdateErrorStateCtor.

    Then update my constructor to inject a ErrorStateMatcher and finally in ngDoCheck, do this:

    ngDoCheck() {
       if (this.ngControl) {
          this.updateErrorState();
       }
    }