首先感谢您提出了一个好问题。
使用 Angular 2.x.x 它将按照您期望的方式工作。
https://plnkr.co/edit/TiOeci5Lr49xvRB5ozHb?p=preview https://plnkr.co/edit/TiOeci5Lr49xvRB5ozHb?p=preview
但在 Angular 4 中引入了新的视图引擎,所有代码都被完全覆盖。
https://plnkr.co/edit/SFruiPXEhMmYDP7WuBbj?p=preview https://plnkr.co/edit/SFruiPXEhMmYDP7WuBbj?p=preview
发生了什么变化?
当事件发生时,角度调用一些称为markForCheck
.
角度2版本
AppView.prototype.markPathToRootAsCheckOnce = function () {
var /** @type {?} */ c = this;
while (isPresent(c) && c.cdMode !== ChangeDetectorStatus.Detached) {
if (c.cdMode === ChangeDetectorStatus.Checked) {
c.cdMode = ChangeDetectorStatus.CheckOnce;
}
if (c.type === ViewType.COMPONENT) {
c = c.parentView;
}
else {
c = c.viewContainer ? c.viewContainer.parentView : null;
}
}
};
角度 4 版本
function markParentViewsForCheck(view) {
var /** @type {?} */ currView = view;
while (currView) {
if (currView.def.flags & 2 /* OnPush */) {
currView.state |= 8 /* ChecksEnabled */;
}
currView = currView.viewContainerParent || currView.parent;
}
}
尽管代码看起来完全不同,但这里没有区别。它从当前组件开始并启用对所有父组件直至根组件的检查。
我突出显示了这句话从当前组件开始因为这正是发生的变化。
Angular 2.x.x 开头为AppComponent
View_App0.prototype.handleEvent_4 = function(eventName,$event) {
var self = this;
self.debug(4,2,3);
self.markPathToRootAsCheckOnce(); // self is AppComponent view
var result = true;
if ((eventName == 'update')) {
var pd_sub_0 = (self.context.onUpdate($event) !== false);
result = (pd_sub_0 && result);
}
return result;
};
Angular 4 开始于CmpComponent
function dispatchEvent(view, nodeIndex, eventName, event) {
var nodeDef = view.def.nodes[nodeIndex];
var startView = nodeDef.flags & 33554432 /* ComponentView */ ? asElementData(view, nodeIndex).componentView : view;
markParentViewsForCheck(startView);
return Services.handleEvent(view, nodeIndex, eventName, event);
}
所以CmpComponent
将被打开检查