Checking the validity of an Angular 2 input using ngModel is simply a matter of getting a reference to the ngModel itself. You get the reference by using the #ref
syntax, assigning it a name, then ngModel
will check all of the validity rules for you.
[00:00] We can make the input required by saying required. Then if there's nothing in here, this field will be marked invalid. Right now there's no way for us to know in our template whether this is invalid, because this is just bound to the value of the input, not the validity of the input.
[00:16] To get the validity we need to access the NG model itself in the template. We can do that by creating a reference to the ng-model. That's going to look something like this. I'm going to call this user name ref, then assign that to the ng-model directive.
[00:33] In my binding I can actually access the user name ref.valid. Hit Save, and you'll see that now this is valid because it's required. If I could lead everything it's not valid, because this requires something.
[00:46] If I type this is true, delete, it's false, because this is a reference to the ng-model it knows if this is valid or invalid.
Hi John, I have two questions:
Lets say I have a form component with a template:
And custom-input component template:
Is it possible to dynamically create / generate the templateReference name
#usernameRef="ngModel"
->#userNameRef-{{index}}="ngModel"
?And second question: if an input element is nested within a component that it self doesn't contain html
form
element (but the parent component does, as in the example) will be the validation errors visible on the parents form#myForm
? Or will be the input and its validation errors effectively hidden by nesting in a child component?(Thank you for great tuts :) )