Home > database >  Angular mat error : How can to prevent displaying error on control touched and display it only on bu
Angular mat error : How can to prevent displaying error on control touched and display it only on bu

Time:07-19

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

CodePudding user response:

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/input-error-state-matcher-example.ts

CodePudding user response:

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

submitted = false;

clickButton() {
  this.submitted = true;
  .
  .
  .
 }
<form >
  <mat-form-field  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>

  • Related