user944513 user944513 - 4 months ago 48
AngularJS Question

how to show validate message in form in angular 2?

I am trying to show validate message in form in angular 2 ? I am getting this error

Cannot read property 'hasError' of undefined

I added these lines

<div *ngIf="username.hasError('required') && username.touched"
class="error-box"> username is required</div>
<div *ngIf="username.hasError('minlength') && username.touched"
class="error-box"> Minimum password length is 8!</div>


here is my code
https://plnkr.co/edit/slhySWT0mJXkloGK1kfO?p=preview

Answer

This should do what you want:

<ion-input type="text" ngControl="username" #username="ngForm"></ion-input>
 <div *ngIf="username.errors?.required && username.touched" 
           class="error-box"> username is required</div>    
       <div *ngIf="username.errors?.minlength && username.touched" 
           class="error-box"> Minimum password length is 8!</div>

Plunker example