I am trying to do validation using the
and
. This works fine when user tabs out of the input without filling. B
GLOBALLY: Show mat-error while typing or touched: Unlike the provided solution, this method will take care of all mat-errors in the app without applying the matcher to each input.
1- Create touched-error-state.matcher.ts file:
import {FormControl, FormGroupDirective, NgForm } from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';
export class TouchedErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.dirty || control.touched));
}
}
2- In app.module import:
import { ErrorStateMatcher } from '@angular/material/core';
import { TouchedErrorStateMatcher } from './your-folder-path/touched-error-state.matcher';
3- Now provide it into the providers:
@NgModule({
providers: [
AuthService,
UserService,
{ provide: ErrorStateMatcher, useClass: TouchedErrorStateMatcher }
],
})
4- Re-Serve the app.