How does [(ngModel)] works with Unidirectional data flow in Angular 2

会有一股神秘感。 提交于 2020-01-04 09:16:22

问题


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"


来源:https://stackoverflow.com/questions/39782146/how-does-ngmodel-works-with-unidirectional-data-flow-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!