What is the difference between #name and [(ngModel)] = "name" in Angular2 by entering a form?

I am a bit confused because for some tutorial use # to get input while some use [(ngModel)]

+12
angular angular2-forms
source share
3 answers

#XXX

#xxx allows you to get a link to an item.

 <input #inp (change)="foo = inp.value"> 

listens for the change event and calls onChange() and passes the inputs to the value property

For two-way snapping you will also need

 <input #inp (change)="foo = inp.value)" [value]="foo = $event"> 

Ngmodel

 <input [(ngModel)]="foo"> 

uses the NgModel directive, which allows you to integrate DOM input elements and custom components into the functionality of an Angular form. It can also be used without form. NgModel is an abstraction for all kinds of elements and components, while the example above ( #inp ) only works for input elements that have a value property and emit a change event.

 [(ngModel)]="foo" 

- short form

 [ngModel]="foo" (ngModelChange)="foo = $event" 

which shows that it is designed for two-way binding.

hint

#xxx returns an instance of a component or directive if the element is not a simple DOM element but an Angular component or has an Angular directive.

+21
source share

SyntaxiC # name is a link to a template that refers to an html object, more information can be found in Angular docs: Guide to Angular Templates

[(NgModel)] establishes a two-way binding to the value of elements and assigns it to a variable.

+5
source share
 <input #inp (change)="foo = inp.value"> 

listens for the change event and calls onChange() and passes a property of input values

For two-way snapping you will also need

 <input #inp (change)="foo = inp.value)" [value]="foo = $event"> 

Ngmodel

 <input [(ngModel)]="foo"> 

uses the NgModel directive, which allows you to integrate DOM input elements and custom components into angular shape functionality. It can also be used without mold. NgModel is an abstraction for all kinds of elements and components, while the above example (#inp) only works for input elements that have a value property and generate a change event.

 [(ngModel)]="foo" 

this is a short form

 [ngModel]="foo" (ngModelChange)="foo = $event" 

which shows that it is for two-way binding.

0
source share

All Articles