首页 > 解决方案 > 以编程方式设置角度 8 时的变化检测计数

问题描述

我知道如何进行变更检测。我阅读了更多关于它的信息。但是我有很多及时的变化检测导致更新 html。这反过来又减慢了浏览器的速度

我可以为角度 8 中的组件设置一次更改检测计数吗?例如,如果我想在 2 分钟内进行一次更改检测。可能吗?

@Component({
    selector: 'my-app',
    template: `<child-comp></child-comp>
                <p> {{name}}</p>`,
    styles: [`h2, p {color:#333;}`]
})
export class AppComponent { 
  // a lot of code
}

标签: angular

解决方案


为了自定义何时运行更改检测,您需要注入 ChangeDetectorRef 并分离。

construtor(private changeDetection: ChangeDetectorRef){
  this.changeDetection.detach();
}

然后您可以使用可观察的计时器定期运行更改检测

timer(12000).subscribe(() => this.changeDetection.detectChanges())

不要忘记在组件销毁时管理可观察订阅和取消订阅。

官方文档:https ://angular.io/api/core/ChangeDetectorRef

编辑

限制变化检测的数量实现 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())
 }

}

推荐阅读