Angular Material - show mat-error on button click

后端 未结 10 1794
刺人心
刺人心 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:14

    See how to use a form with a custom ErrorStateMatcher

    If you wish to override this behavior (e.g. to show the error as soon as the invalid control is dirty or when a parent form group is invalid), you can use the errorStateMatcher property of the matInput. The property takes an instance of an ErrorStateMatcher object. An ErrorStateMatcher must implement a single method isErrorState which takes the FormControl for this matInput as well as the parent form and returns a boolean indicating whether errors should be shown. (true indicating that they should be shown, and false indicating that they should not.)

    I would make a separate file such as default.error-matcher.ts

    /** Error when invalid control is dirty or touched*/
    export class MyErrorStateMatcher implements ErrorStateMatcher {
      isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        return !!(control && control.invalid && (control.dirty || control.touched));
      }
    }
    

    Then in the TS file add:

    matcher = new MyErrorStateMatcher();
    

    Then change the input to use matcher:

    
        
        Due Date is required for Tasks
    
    

提交回复
热议问题