【发布时间】:2017-03-23 17:17:16
【问题描述】:
我在 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()方法的重要性。
【问题讨论】:
-
对于上述组件,我还添加了一个带有点击事件处理程序的按钮, 我的期望是,当用户单击按钮,将进行更改检测,并且视图将更新为最新的 numberOfTicks,但即使是现在,也只有在 test() 函数中调用 markForCheck 时才会更新视图。希望我的问题有意义..
标签: angular