Difference between [(ngModel)] and [ngModel] for binding state to property?
Angular2+ data flow:
In Angular the data can flow between the model (component class ts.file) and view (html of the component) in the following manners:
- From the model to the view.
- From the view to the model.
- Data flows in both directions, also known as 2 way data binding.
Syntax:
model to view:
<input type="text" [ngModel]="overRideRate">
This syntax is also known as property binding. Now if the overRideRate
property of the input field changes the view automatically will get updated. However if the view updates when the user enters a number the overRideRate
property will not be updated.
view to model:
(input)="change($event)" // calling a method called change from the component class
(input)="overRideRate=$event.target.value" // on input save the new value in the title property
What happens here is that an event is triggered (in this case input event, but could be any event). We then can call methods of the component class or directly save the property in a class property.
2-way data binding:
<input [(ngModel)]="overRideRate" type="text" >
The following syntax is used for 2-way data binding. It is basically a syntactic sugar for both:
- Binding model to view.
- Binding view to model
Now something changes inside our class this will reflect our view (model to view), and whenever the user changes the input the model will be updated (view to model).
[ngModel]="currentHero.name"
is the syntax for one-way binding, while,
[(ngModel)]="currentHero.name"
is for two-way binding, and the syntax is compound from:
[ngModel]="currentHero.name"
and (ngModelChange)="currentHero.name = $event"
If you only need to pass model, use the first one. If your model needs to listen change events (e.g. when input field value changes), use the second one.
[(ngModel)]="overRideRate"
is the short form of [ngModel]="overRideRate"
(ngModelChange)="overRideRate = $event"
[ngModel]="overRideRate"
is to bindoverRideRate
to theinput.value
(ngModelChange)="overRideRate = $event"
is to updateoverRideRate
with the value ofinput.value
when thechange
event was emitted.
Together they are what Angular2 provides for two-way binding.
It's quite simple
[] => component to template
() => template to component
[(ngModel)]
is a contracted form of [ngModel]="currentHero.name" (ngModelChange)="currentHero.name=$event">
More detail here : https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngModel