【问题标题】:Angular ChangeDetectionStrategy.OnPush with child component emitting an event带有发射事件的子组件的 Angular ChangeDetectionStrategy.OnPush
【发布时间】:2017-06-17 17:04:06
【问题描述】:

我不明白为什么子组件的变更检测会在这种情况下运行:

import { Component, ChangeDetectionStrategy } from '@angular/core'

@Component({
  selector: 'app-root',
  template: `
    <cmp [ticks]="ticks" (update)="onUpdate($event)"></cmp>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {

  ticks = 0;

  onUpdate(event) {
    console.log(this.ticks);
  }
}


import { Component, ChangeDetectionStrategy, OnInit, Input, Output, EventEmitter, OnChanges } from '@angular/core';

@Component({
  selector: 'cmp',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p>Number of ticks: {{ticks}}</p>
`
})
export class CmpComponent implements OnInit, OnChanges {
  @Input('ticks') ticks: number;
  @Output() update: EventEmitter<number> = new EventEmitter();

  ngOnInit() {
    setInterval(() => {
      this.ticks++;
      this.update.emit(this.ticks);
    }, 1000);
  }

  ngOnChanges() {
    console.log('changed');
  }
}

当我运行时,子视图中的“滴答数”会更新。

当我在父级中删除监听事件时,它不会更新视图。

我的理解如下:

由于父级实现了 OnPush 策略,它在侦听从子级发出的事件时触发更改检测。在接收到事件时,它不会改变 'tick',因此子组件的 @Input() 不会更新。然而,也实现 OnPush 策略的子组件更新了它的视图。因此,它的行为就好像它的 @Input 发生了变化。

根据我的研究:

使用 OnPush 策略,如果出现以下情况,则会对组件进行更改检测:

  • 在组件本身上接收到绑定事件。
  • @Input() 已更新
  • |异步管道收到一个事件
  • “手动”调用了更改检测

这些似乎都不适用于子组件。

有什么解释吗?非常感激。

【问题讨论】:

    标签: angular


    【解决方案1】:

    首先感谢一个好问题。

    使用 angular 2.x.x,它将按您期望的方式工作。

    https://plnkr.co/edit/TiOeci5Lr49xvRB5ozHb?p=preview

    但是在 angular4 中引入了新的视图引擎并且所有代码都被完全覆盖了。

    https://plnkr.co/edit/SFruiPXEhMmYDP7WuBbj?p=preview

    发生了什么变化?

    当事件发生时,角度调用一些称为 markForCheck 的方法。

    angular 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;
        }
      }
    };
    

    angular 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将被打开以供检查

    【讨论】:

    • 感谢您的精彩回答。
    猜你喜欢
    • 1970-01-01
    • 2018-06-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多