Performance: ngDoCheck for custom change detection
HIGH IMPACT
This affects the interaction responsiveness and rendering speed by controlling how often Angular checks for changes in components.
export class MyComponent implements DoCheck { private oldValue: any; ngDoCheck() { if (this.hasChanged(this.data, this.oldValue)) { this.oldValue = this.data; this.updateView(); } } hasChanged(newVal: any, oldVal: any) { // shallow reference comparison return newVal !== oldVal; } updateView() { // update UI only when needed } }
export class MyComponent implements DoCheck { ngDoCheck() { // heavy or frequent checks this.expensiveCheck(); } expensiveCheck() { // complex logic running every change detection cycle } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy logic in ngDoCheck every cycle | Many unnecessary DOM checks | Multiple reflows if DOM updated unnecessarily | High paint cost due to blocking | [X] Bad |
| Optimized ngDoCheck with change comparison | Minimal DOM updates only on real changes | Single reflow per actual change | Low paint cost, smooth rendering | [OK] Good |