了解角度2中的变化检测 [英] Understanding change detection in angular 2

查看:75
本文介绍了了解角度2中的变化检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 2文档中遇到了以下示例

@Component({
  selector: 'cmp',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `Number of ticks: {{numberOfTicks}}`
})
class Cmp {
  numberOfTicks = 0;
  constructor(ref: ChangeDetectorRef) {
    setInterval(() => {
      this.numberOfTicks ++
     // the following is required, otherwise the view will not be updated
     this.ref.markForCheck();
    }, 1000);
  }
}

如上所述,当changeDetection更改为ChangeDetectionStrategy.OnPush时,仅在"this.ref.markForCheck();"时更新视图.被调用.

任何人都可以在这里解释markForCheck()方法的重要性.

解决方案

使用ChangeDetectionStrategy.OnPush进行Angular运行更改检测,当在@Input()中进行更新时,收到了Angular侦听的DOM事件,或者接收了异步管道()收到一个新值.

例如,如果您从服务预订了一个可观察对象并更新了组件的状态,则不会更新对此状态的绑定,因为上面的列表未涵盖此内容.如果您调用this.ref.markForCheck(),则告诉Angular它应该运行更改检测,因为实际上存在需要更新的更改(这也是异步管道所执行的操作).

其他情况是,如果您显式(this.zone.runOutsideAngular())或出于某些其他原因,在Angulars区域外运行的代码修改了组件的状态,则也不会涉及到该状态(即使代码是事件处理程序也是如此)./p>

I have come across below example in Angular 2 documentation

@Component({
  selector: 'cmp',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `Number of ticks: {{numberOfTicks}}`
})
class Cmp {
  numberOfTicks = 0;
  constructor(ref: ChangeDetectorRef) {
    setInterval(() => {
      this.numberOfTicks ++
     // the following is required, otherwise the view will not be updated
     this.ref.markForCheck();
    }, 1000);
  }
}

As mentioned above , when changeDetection is to ChangeDetectionStrategy.OnPush , the view gets updated only when "this.ref.markForCheck();" is invoked.

Can any one please explain the importance of markForCheck() method here.

解决方案

With ChangeDetectionStrategy.OnPush Angular runs change detection, when in @Input() was updated, a DOM event Angular listens to was received, or the async pipe (| async) received a new value.

If you for example subscribe to an observable from a service and update the status of the component, bindings to this status won't be updated, because this is not covered by above list. If you call this.ref.markForCheck() you tell Angular that it should run change detection because there actually are changes that need to be updated (that's also what the async pipe does).

Other cases are if you explicitly (this.zone.runOutsideAngular()) or for some other reasons code runs outside Angulars zone modifies the status of the component, this also won't be covered (even when the code is an event handler).

这篇关于了解角度2中的变化检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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