Can someone explain me this syntax in Angular form #name="ngModel"

Viewed 307

I created a template form using Angular and I wanted to show a message if the field is not correct.

Here is the input :

<input type="text" id="task-libelle" name="libelle" class="form__input" ngModel required>

And here is the error message :

<p class="error-message" *ngIf="libelle.invalid || libelle.pristine">This field must not be empty</p>

Like this, I have an error message which tells me that "libelle" does not exist on type "MyComponent".

In order to make it work, I had to add ngModel #libelle="ngModel"

<input type="text" id="task-libelle" name="libelle" class="form__input" ngModel #libelle="ngModel" required>

But I have no idea why and what does exactly do this #libelle="ngModel" with the ngModel attribute still be here (if i remove the ngModel attribute, I get an error NG8003: No directive found with exportAs 'ngModel').

Can someone explain this to me please ?

2 Answers

the #name is a template reference.

you can now use it in your template as an object representing the html element:

<div #name> 123 </div>
<p> {{ name.innerHTML }} </p>

that works fine if you want the html element.

In template forms, you would prefer to get the a reference of the FormControl to be able to read the form control's state. you do so by using #name="ngModel"

  <input #name="ngModel" type="text" name="required" required />
  <p> is control valid: {{ name.valid }} </p>

in the above example, we have an input with a required validator. the element will be considered invalid as long as it does not contain any text.

read more: https://angular.io/guide/forms#show-and-hide-validation-error-messages

<input #libelle ...> would create a local variable named libelle that provides access to the input element instance in data-binding and event-binding expressions in the HTML template

<input ngModel #libelle="ngModel" ...> does pretty much the same thing except it provides access to the ngModel directive rather than the input element.

The general syntax is #localvar[="directiveName"].

See documentation: https://angular.io/guide/template-reference-variables

Related