Performance: ngDoCheck for custom change detection
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 |
ngDoCheck lifecycle hook in Angular?ngDoCheckngDoCheck allows developers to add custom checks to detect changes Angular might miss.ngDoCheck in an Angular component?ngDoCheck() { ... }.items = [1, 2, 3];
ngDoCheck() {
if (this.items.length !== this.oldLength) {
console.log('Items changed');
this.oldLength = this.items.length;
}
}items.push(4) is called and Angular runs change detection?oldLengththis.oldLength but it is never initialized, so it's undefined initially.items.push(4)this.items.length becomes 4, and 4 !== undefined is true, so 'Items changed' is logged. No error occurs.ngDoCheck implementation:ngDoCheck() {
if (this.data !== this.oldData) {
this.processData();
this.oldData = this.data;
}
}processData() never be called even if data changes internally (like modifying a property inside an object)?!== operator checks if two variables point to different objects, not if the content inside objects changed.ngDoCheck logicdata is the same object but its properties change, this.data !== this.oldData is false, so processData() is not called.profile in ngDoCheck. Which approach correctly detects changes to any property inside profile without replacing the whole object?Pass the test and this pattern moves unknown