Use errorStateMatcher as directive


April 2019


9 time


I have simple material input and for that input, I'm using material errorStateMatcher which help me to show mat-error dynamically and not on the input blur.

<input matInput

and inside the component:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.dirty || control.touched));

matcher = new MyErrorStateMatcher();

Is it possible to make errorStateMatcher as a directive errorStateMatcherDirective and don't use MyErrorStateMatcher class in every controller and instead use it like this:

<input matInput

1 answers


A solution that lets you control which MatInput and which ErrorStateMatcher you want to pass to the ErrorStateMatcherDirective:

  selector: '[errorStateMatcherDirective]'
export class ErrorStateMatcherDirective {
  @Input() input: MatInput;
  @Input() matcher: ErrorStateMatcher;

  constructor() {
    this.input._defaultErrorStateMatcher = this.matcher;

<input matInput errorStateMatcherDirective #matInput="matInput" [input]="matInput" [matcher]="matcher"/>