问题
Angular 2 supports unidirectional data flow, would appreciate if someone could explain or give some references of a resource that explains unidirectional data flow in detail with diagrams.
回答1:
parent to child
Angular2 has only uni-directional data-binding from parent to child using this binding syntax
// child
@Input() childProp;
<!-- parent -->
[childProp]="parentProp"
These bindings are updated by Angular2's change detection.
child to parent
Changes from child to parent are propagated by events emitted by outputs and are unrelated to change detection.
// child
@Output() childPropChanged = new EventEmitter();
clickHandler() {
this.childPropChange.emit('someValue');
}
<!-- parent -->
(childPropChange)="parentProp = $event"
Angulars change detection is invoked again after an event or another async call was completed.
uni-directional data flow
Uni-directional data flow means that change detection can't cause cycles. Change detection is executed from the root component towards the leaf components and when all leaf components are updated, the change detection cycle is completed.
prodMode/devMode
When change detection itself causes a change, then an error is thrown in devMode (see also What is difference between production and development mode in Angular2?) which prevents that uni-directional data-flow is violated.
two-way binding
There isn't really two-way binding in Angular2. The two-way binding syntax
[(childProp)]="parentProp"
is only syntactic sugar to combine parent-to-child and child-to-parent binding shown above to a single binding.
来源:https://stackoverflow.com/questions/39708018/angular2-unidirectional-data-flow