I have seen that in angular 2 instead of using ngModel I can put something like this:
<input type="text" name="txtnombre" #Nombre />
<button (click) = "validarNombre(#Nombre)" > Validar </ button>
I don't quite understand when to use this type of variable with # and what is the advantage of using this instead of this
<input type="text" name="txtnombre" [(ngModel)]="nombre" />
Could someone explain to me? Thank you.
The expression
#nombre
on an html element creates the reference on the element. For example when you do:The reference of the called html element is being sent
#Nombre
, in this case the input.Now, one valid reason you might want to do this is to minimize the use of bindings in Angular if you don't need to. If you were to use en
ngModel
, angular would have to do the binding to watch for changes ininput
it but with the element reference that's not necessary. However, it is not good to perform modification operations on an element with its reference unless necessary, since Angular has a wide variety of directives for this.