变更检测机制
申远 2021-03-22 Angular
# 变更检测机制
# 简介
Angular 各种视图的基础类,提供变更检测功能。 变更检测树会收集要检查的所有视图。 使用这些方法从树中添加或移除视图、初始化变更检测并显式地把这些视图标记为脏的,意思是它们变了、需要重新渲染。
angular的变更检测是可以更改的,其核心内容是更改@component的changeDetection
ChangeDetectionStrategy
: Default和onPush
方法 | 说明 |
---|---|
markForCheck() | 当视图使用 OnPush变更检测策略时,把该视图显式标记为已更改,以便它再次进行检查 |
detach() | 从变更检测树中分离开视图。 已分离的视图在重新附加上去之前不会被检查。 与 detectChanges() 结合使用,可以实现局部变更检测 |
detectChanges() | 检查该视图及其子视图。与 detach 结合使用可以实现局部变更检测。 |
reattach() | 把离开的视图重新附加到变更检测树上。 |
checkNoChanges() | 检查变更检测器及其子检测器,如果检测到任何更改,则抛出异常。 |
# 使用场景
1:提高性能
2:有大量数据频繁渲染
# 使用
1: 修改检测机制 手动更改内容触发检测
import { ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: 'hello.component.html',
changeDetection:ChangeDetectionStrategy.OnPush
})
constructor(
public cdr:ChangeDetectorRef
) {
this.cdr.markForCheck()
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
2: 分离检测树和视图, 手动脏检查此时不需要修改changeDetection
为OnPush
this.cdr.detach();
this.cdr.detectChanges()
this.cdr.reattach()
1
2
3
2
3
# 小结
更改机制后,其引用的组件也会更改为相应的机制,例如父组件分离了检测树,那么引用的子组件也需要检测