为什么changeDetectionStrategy.OnPush不会在@Input属性更改中更新但更新@Output触发器属性更改? [英] Why changeDetectionStrategy.OnPush does not update in @Input attribute change but does update @Output trigger attribute change?

查看:93
本文介绍了为什么changeDetectionStrategy.OnPush不会在@Input属性更改中更新但更新@Output触发器属性更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个 plunker

孙子组件

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

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

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

子组件

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')
}

父组件

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

我看到按钮时被点击

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

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

This is confusing since I expect only the parent view to get updated since changeDetection: ChangeDetectionStrategy.OnPush, is config in child component.

我想我错过了什么,有人能指出我的意思吗正确的方向?

I think I am missing something, can someone point me the right direction?

谢谢

推荐答案

所有原生事件标志着路径到根组件进行一次检查。在孙子组件的模板中,您使用原生点击事件:

All native events mark the path to the root component for check once. Here in the template of Grandchild Component you're using native click event:

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

因此,组件的层次结构标记为支票一次。

Hence the hierarchy of components is marked for the check once.

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

有关变化检测的最全面说明,请阅读:

For the most comprehensive explanation of change detection read:

  • Everything you need to know about change detection in Angular

了解更多关于 markForCheck 请参阅此答案并阅读本文:

To learn more about markForCheck see this answer and read this article:

  • If you think ngDoCheck means your component is being checked — read this article

这篇关于为什么changeDetectionStrategy.OnPush不会在@Input属性更改中更新但更新@Output触发器属性更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆