Reputation: 3627
How to display single error correctly on validating multiple errors using ng if else in template driven form.
<form>
<mat-card>
<mat-card-content>
<mat-form-field>
<input id="email" name="email" #ref_email="ngModel" matInput type="email" email placeholder="Email" [(ngModel)]="email" required>
<mat-error *ngIf="!ref_email.valid && ref_email.errors.required">
Email is required
</mat-error>
<mat-error *ngIf="!ref_email.valid && ref_email.errors.email">
Email is not valid
</mat-error>
</mat-form-field>
</mat-card-content>
</mat-card>
</form>
Upvotes: 5
Views: 6947
Reputation: 2499
First of all even on template driven forms you need to reference your form with a html property something like this: <form #userForm="ngForm">
After that you can check to the errors of the referenced form:
<mat-error *ngIf="userForm.controls['email']?.errors?.required">
Email is required.
</mat-error>
<mat-error *ngIf="userForm.controls['email']?.errors?.email">
Email is not valid.
</mat-error>
Upvotes: 4