Check ngModel Validation in Angular 2

Share this video with your friends

Send Tweet

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.

felikf
felikf
~ 7 years ago

Hi John, I have two questions:

Lets say I have a form component with a template:

<form #myForm="ngForm">
    <custom-input [index]="1">...</custom-input>
    <custom-input [index]="1">...</custom-input>
</form>

And custom-input component template:

<input #usernameRef-{{index}}="ngModel" name="username{{index}}" [(ngModel)]="username" ... </input>

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 :) )