2

NOTE: this is not the same question as my other question at https://stackoverflow.com/questions/38356330/how-to-use-pattern-validation-in-angular-2-based-on-ngmodel-template-model-driv

This is my code (Angular 2 rc2 app with deprecated forms):

<form #myForm="ngForm">
    <input id="inputControlX" ngControl="inputControlX" pattern="abcd">
    {{inputControlX.valid}}
</form>

inputControlX is validated correctly (ng-invalid class is added to the input). However when I add

 {{inputControlX.valid}}

or

{{myForm.inputControlX.valid}}

or

{{ngForm.inputControlX.valid}}

I keep getting an error: can't read property valid of undefined. On the other hand adding (as in this answered question) #inputControlX="ngForm", makes it work (even without ngControl)

Why is this necessary?

1 Answer 1

2

You have to use Elvis operator / ngIf directive here, Because when angular tries to evaluate binding of the page, myForm object haven't initialized yet. So while evaluating myForm.inputControlX.valid expression, myForm object isn't defined that time, so it throws an error.

{{myForm?.inputControlX?.valid}}
//OR    
<span *ngIf="myForm"> {{myForm.inputControlX.valid}}</span>
Sign up to request clarification or add additional context in comments.

5 Comments

thank for the answer. can you please clarify why wirh #tempvar works? after that I'll accept the answer
You mean to say, linked answer?
@when you use #tempvar="ngForm" angular internally creates an form object & put all the fields inside a that form object which has ngModel directive.. and all the validation property are available on each form level object, you can also refer to this answer of Angular1, the basic fundamental is the same
@dragonmnl let me know if you need anything else?
thanks for the further explanations. answer accepted

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.