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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

this is elvis (?) operator, this prevents throwing error when variable is undefined
Sorry, wrong position. errors can be null, username not. And yes, like @PardeepJain mentioned this is to avoid error messages when errors is null. ?. is called safe-navigation or Elvis operator which only evaluates the expression after ?. when the part before is not null
Also some way is necessary to make username available. I updated my answer (adding #username="ngForm" or what @yurzui explained in his answer)

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.