SMH
SMH

Reputation: 1099

Angular 2 Show error message only when input class is "ng-touched"?

How to Show error message in Angular 2.2.0 only when the input has class ng-touched?

<form  #myForm='ngForm' (ngSubmit)='onSubmit(submit)' (submit)="preventDefault($event)">
    <input type="text" name="firstName" ngModel required>
    <div class="error-mesg"> Name is required </div>
     <button type="submit" [disabled]="!myForm.form.valid">
    </form>

Upvotes: 2

Views: 4785

Answers (1)

Jecfish
Jecfish

Reputation: 4189

First, you need to have a variable to hold firstName model #fistName="ngModel". Then, you can read the firstName status like pristine, dirty, touched, valid, etc.

<input type="text" name="firstName" ngModel required 
    #fistName="ngModel">
<div class="error-mesg" [hidden]="fistName.valid || (fistName.pristine && !myForm.submitted)">
    Name is required
</div>

For more detail explanation, read this article here: https://scotch.io/tutorials/using-angular-2s-template-driven-forms

Upvotes: 4

Related Questions