angular - 以编程方式设置角度 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
}
解决方案
为了自定义何时运行更改检测,您需要注入 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())
}
}
推荐阅读
- java - 如何同步访问 Java Hashmap 中的值?
- javascript - 当使用“nightwatch-api”上下文/客户端调用时,.elements 在黄瓜的 Given/Then 步骤方法中不起作用
- r - 根据列表名称列表重命名列表列表的第一列
- python-3.x - 在Python中返回包含两个元素的列表中另一个元素的快速方法
- rust - Rust 中未解决的导入。找不到箱子
- javascript - 如何将 ScrollView 中的无限内容与 React-Native 对齐?
- java - 我正在尝试读取文本文件并将其存储在对象数组列表中
- cypress - 如何从赛普拉斯的 react-date-picker 中选择或添加日期?
- r - “条件”列不存在。即使该列显然存在?
- google-maps - 中国支持谷歌地图