How does [(ngModel)] works with Unidirectional dat

2019-07-08 09:56发布

问题:

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

回答1:

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"