Mitul Sheth
Mitul Sheth

Reputation: 81

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

Upvotes: 0

Views: 1522

Answers (2)

Saba Sojoodi
Saba Sojoodi

Reputation: 57

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>

Upvotes: 0

Antoniossss
Antoniossss

Reputation: 32507

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

Upvotes: 1

Related Questions