Friday, May 6, 2016

ngModel in angular2



The punctuation in the binding syntax, [()], is a good clue to what's going on.

In a Property Binding, a value flows from the model to a target property on screen. We identify that target property by surrounding its name in brackets, []. This is a one-way data binding from the model to the view.

In an Event Binding, we flow the value from the target property on screen to the model. We identify that target property by surrounding its name in parentheses, (). This is a one-way data binding in the opposite direction from the view to the model.

No wonder Angular chose to combine the punctuation as [()] to signify a two-way data binding and a flow of data in both directions.

In fact, we can break the NgModel binding into its two separate modes as we do in this example of the "Name"

<input type="text" class="form-control" required
[ngModel]="model.name"
(ngModelChange)="model.name = $event" >
TODO: remove this: {{model.name}}

The Property Binding should feel familiar. The Event Binding might seem strange.

The ngModelChange is not an <input /> element event. It is actually an event property of the NgModel directive. When Angular sees a binding target in the form [(x)], it expects the x directive to have an x input property and an xChange output property.
The other oddity is the template expression, model.name = $event. We're used to seeing an $event object coming from a DOM event. The ngModelChange property doesn't produce a DOM event; it's an Angular EventEmitter property that returns the input box value when it fires — which is precisely what we should assign to the model's name property.

We almost always prefer [(ngModel)]. We might split the binding if we had to do something special in the event handling.

No comments: