Performance: Triggering detection manually
This affects how quickly Angular updates the UI after data changes, impacting interaction responsiveness and visual stability.
import { ChangeDetectorRef } from '@angular/core'; constructor(private cdr: ChangeDetectorRef) {} updateData(newData: any) { this.data = newData; this.cdr.detectChanges(); }
setTimeout(() => { this.data = newData; }); // relies on Angular zone to detect changes
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Automatic zone-triggered detection | Many checks on all components | Multiple reflows if many changes | Higher paint cost due to frequent updates | [X] Bad |
| Manual detectChanges call | Checks only updated components | Single reflow per update | Lower paint cost with targeted updates | [OK] Good |
ChangeDetectorRef.detectChanges() in Angular?ChangeDetectorRef in an Angular component constructor?private cd: ChangeDetectorRef tells Angular to inject the service automatically.import { ChangeDetectorRef } from '@angular/core';
@Component({ selector: 'app-demo', template: '{{counter}}' })
export class DemoComponent {
counter = 0;
constructor(private cd: ChangeDetectorRef) {}
increment() {
setTimeout(() => {
this.counter++;
this.cd.detectChanges();
}, 1000);
}
}increment()?constructor(private cd: ChangeDetectorRef) {}
updateData() {
this.data = fetchDataFromOutsideAngular();
// Missing detectChanges call here
}detectChanges() is not called after updating data?Pass the test and this pattern moves unknown