Use errorStateMatcher as directive

Refresh

6 days ago

Views

9 time

0

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
       [errorStateMatcher]="matcher"/>

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
       errorStateMatcherDirective/>

1 answers

1

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

@Directive({
  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"/>