5

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>

enter image description here

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

1 Comment

first line *ngIf="*ngIf="

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.