angularangular-materialmat-error

Angular mat error : How can to prevent displaying error on control touched and display it only on button click


I need to display validation error only on button click not on control touched


Solution

  • you need to define a boolean variable for example [submitted]

    submitted = false;
    
    clickButton() {
      this.submitted = true;
      .
      .
      .
     }
    <form class="example-form">
      <mat-form-field class="example-full-width" appearance="fill">
        <mat-label>Email</mat-label>
        <input type="email" matInput [formControl]="emailFormControl"
               [errorStateMatcher]="matcher && submitted"
               placeholder="Ex. pat@example.com">
        <mat-hint>Errors appear instantly!</mat-hint>
        <mat-error 
        *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required') && submitted">
          Please enter a valid email address
        </mat-error>
        <mat-error *ngIf="emailFormControl.hasError('required') && submitted">
          Email is <strong>required</strong>
        </mat-error>
      </mat-form-field>
    </form>