Angular Material - show mat-error on button click

后端 未结 10 1824
刺人心
刺人心 2021-02-02 07:48

I am trying to do validation using the and . This works fine when user tabs out of the input without filling. B

10条回答
  •  礼貌的吻别
    2021-02-02 08:20

    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.

提交回复
热议问题