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,
[ngModel] = 'myName'
, and(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 anx
input property for property binding and anxChange
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"