Reputation: 15548
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?
Upvotes: 2
Views: 2292
Reputation: 136154
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>
Upvotes: 2