Angular 以编程方式设置时间为8时的更改检测计数
我知道如何进行变更检测。我读了更多关于它的内容,但是我有很多及时的变化检测,这导致了html的更新,这反过来又减慢了浏览器的速度 我可以设置角度为8的组件在时间上的变化检测计数吗?例如,如果我想在2分钟内进行一次变化检测。可能吗Angular 以编程方式设置时间为8时的更改检测计数,angular,Angular,我知道如何进行变更检测。我读了更多关于它的内容,但是我有很多及时的变化检测,这导致了html的更新,这反过来又减慢了浏览器的速度 我可以设置角度为8的组件在时间上的变化检测计数吗?例如,如果我想在2分钟内进行一次变化检测。可能吗 @Component({ selector: 'my-app', template: `<child-comp></child-comp> <p> {{name}}</p>`
@Component({
selector: 'my-app',
template: `<child-comp></child-comp>
<p> {{name}}</p>`,
styles: [`h2, p {color:#333;}`]
})
export class AppComponent {
// a lot of code
}
@组件({
选择器:“我的应用程序”,
模板:`
{{name}`,
样式:[`h2,p{color:#333;}`]
})
导出类AppComponent{
//很多代码
}
为了自定义何时运行更改检测,您需要注入ChangeDetectorRef并分离
construtor(private changeDetection: ChangeDetectorRef){
this.changeDetection.detach();
}
然后,您可以使用可观察计时器定期运行更改检测
timer(12000).subscribe(() => this.changeDetection.detectChanges())
不要忘记在组件销毁时管理可观察订阅和取消订阅
官方文件:
编辑
限制更改检测的数量
实现OnChanges
private countChanges =0;
ngOnChanges(changes: SimpleChanges){
this.countChanges++;
if(this.countChanges > 1){
this.changeDetection.detach();
this.countChanges = 0;
timer(12000).pipe(take(1)).subscribe(() => this.changeDetection.reattach())
}
}
如果此时没有根组件的更改检测,则此版本是不好的