为什么 changeDetectionStrategy.OnPush 在@Input 属性更改时不更新,但更新@Output 触发属性更改?

Why changeDetectionStrategy.OnPush does not update in @Input attribute change but does update @Output trigger attribute change?

考虑这个plunker

Grandchild Component

<button (click)="back2click()"></button>

@Input() from2;
@Output()
back2 = new EventEmitter<any>();

back2click() {
   this.back2.emit('hi');
}

Child Component

changeDetection: ChangeDetectionStrategy.OnPush,

<my-app-n2 [from2]="from1" (back2)="handleback2($event)"></my-app-n2>

@Input() from1;
@Output() back1 = new EventEmitter<any>();

handleback2() {
    this.back1.emit('hi')
}

Parent Component

<my-app-n1 [from1]="from" (back1)="handleback1($event)"></my-app-n1>
handleback1 () {
    this.from.name = 'handline4';
}

我看到当 button 被点击时

back2click -> emit -> handleback2 -> emit -> handleback1 
    -> attribute is updated -> all child view are updated

这令人困惑,因为我希望只有父视图得到更新,因为 changeDetection: ChangeDetectionStrategy.OnPush, 是子组件中的配置。

我想我遗漏了什么,有人能给我指明正确的方向吗?

谢谢

所有原生事件都会标记到根组件的路径以供检查一次。在 Grandchild Component 的模板中,您使用的是原生 click 事件:

<button (click)="back2click()"></button>

因此组件的层次结构被标记为检查一次。

   Root Component -> ViewState.ChecksEnabled = true
     |
    ...
     |
   Parent  -> ViewState.ChecksEnabled = true
     |
     |
   Child  (onPush)  -> ViewState.ChecksEnabled = true
     |
     |
   Grand child (event triggered here) -> markForCheck() -> ViewState.ChecksEnabled = true

有关更改检测的最全面说明,请阅读:

要了解有关 markForCheck 的更多信息,请参阅 并阅读这篇文章: