javascript / expert
Snippet
Granular Performance Control with ChangeDetectorRef Detachment
By calling 'detach()' on the ChangeDetectorRef, you remove the component from the automatic change detection tree. This is essential for high-performance scenarios like real-time graphs or WebGL wrappers, where you only want to trigger UI updates manually via 'detectChanges()' based on specific business logic logic.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component({ selector: 'heavy-graph', template: `<div>{{ data }}</div>` })export class HeavyGraphComponent {data = 0;constructor(private cd: ChangeDetectorRef) {this.cd.detach();}updateData(val: number) {this.data = val;if (val % 10 === 0) {this.cd.detectChanges();}}}
angular
Breakdown
1
this.cd.detach();
Disables automatic change detection for this component and its children.
2
this.cd.detectChanges();
Manually triggers a localized change detection check for the current view.