2

Angular 2 supports unidirectional data flow, one way at a time. How does two way data binding [(ngModel)] works in Angular2 ?

Shivanka
  • 723
  • 2
  • 8
  • 21

1 Answers1

3

Angular2 comprehends [(ngModel)] = myName as a property + event binding and as a collapsed version of,

  1. [ngModel] = 'myName', and
  2. (ngModelChange) = 'updateMyNameValue(myName)'

Their unidirectional data flow policy might as well as take the expanded version of it such as setting the scope variable explicitly by the inputs event when the value is changed and vice-versa, so as this syntactic sugar version of it might look almost like

myName = '';
function updateMyNameValue(elem) {
   // find scope variable of `myName` and update it
   // find element in view and update it
}
// <input type="text" onchange="updateMyNameValue(this)" value="" />

According to the docs,

[(ngModel)] is a specific example of a more general pattern in which Angular "de-sugars" the [(x)] syntax into an x input property for property binding and an xChange output property for event binding. Angular constructs the event property binding's template statement by appending =$event to the literal string of the template expression.

[(x)]="e" <==> [x]="e" (xChange)="e=$event"
choz
  • 17,242
  • 4
  • 53
  • 73
  • so, where does the event handler being implemented ? inside the component ? – Shivanka Sep 30 '16 at 01:36
  • @Shivanka No, they have their own way for each form controls such as `inputs, selects, multiple selects, etc..` to implement the event handler in their directives. – choz Sep 30 '16 at 01:49
  • in a situation where I want to override the event handler in two way data binding, how do I implement such a functionality. – Shivanka Oct 02 '16 at 03:01
  • @Shivanka You can set the event handler explicitly by setting `(ngModelChange)`. If you're still unclear what I'm talking about, try clicking the docs link I gave.. It might help. – choz Oct 02 '16 at 03:06