我在 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() 方法的重要性吗?
With ChangeDetectionStrategy.OnPush
Angular 运行更改检测,当处于@Input()
已更新、接收到 Angular 侦听的 DOM 事件、或异步管道 (| async
) 获得了一个新值。
例如,如果您从服务订阅可观察对象并更新组件的状态,则与此状态的绑定将不会更新,因为上面的列表未涵盖这一点。如果你打电话this.ref.markForCheck()
你告诉 Angular 它应该运行更改检测,因为实际上存在需要更新的更改(这也是异步管道的作用)。
其他情况是如果您明确 (this.zone.runOutsideAngular()
)或由于某些其他原因,在 Angulars 区域之外运行的代码会修改组件的状态,这也不会被覆盖(即使代码是事件处理程序)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)