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

1.2k Views Asked by At

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

2

There are 2 best solutions below

0
Saba Sojoodi On BEST ANSWER

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. [email protected]">
    <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>

0
Antoniossss On

Use error state matcher, which will allow you to freely specify when control should be in error state despite its touched state and validation errors.

Official material component docs

https://stackblitz.com/angular/vkgmbaepodbg?file=app%2Finput-error-state-matcher-example.ts