Sometimes Angular's automatic change detection does not catch all changes. ngDoCheck lets you check for changes yourself and react to them.
ngDoCheck for custom change detection in Angular
Introduction
Syntax
Angular
ngDoCheck(): void { // Your custom change detection logic here }
This method is part of Angular's DoCheck lifecycle interface.
Angular calls ngDoCheck frequently, so keep logic efficient.
Examples
Angular
ngDoCheck(): void { if (this.oldValue !== this.newValue) { console.log('Value changed!'); this.oldValue = this.newValue; } }
Angular
ngDoCheck(): void { const currentLength = this.items.length; if (this.oldLength !== currentLength) { console.log('Array length changed!'); this.oldLength = currentLength; } }
Sample Program
This component uses ngDoCheck to detect when the items array changes length. When you click the button, a new item is added, and the console logs the change.
Angular
import { Component, DoCheck } from '@angular/core'; @Component({ selector: 'app-custom-check', template: ` <h2>Custom Change Detection Example</h2> <button (click)="addItem()">Add Item</button> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> ` }) export class CustomCheckComponent implements DoCheck { items: string[] = ['Apple', 'Banana']; oldLength = this.items.length; ngDoCheck(): void { if (this.oldLength !== this.items.length) { console.log('Items array changed!'); this.oldLength = this.items.length; } } addItem() { this.items.push('Orange'); } }
Important Notes
Do not put heavy or slow code inside ngDoCheck because it runs often.
Use ngDoCheck only when Angular's default change detection is not enough.
Summary
ngDoCheck lets you run your own checks for changes.
It is useful for detecting changes Angular misses, like in arrays or objects.
Keep the code inside ngDoCheck fast and simple.
Practice
1. What is the main purpose of the
ngDoCheck lifecycle hook in Angular?easy
Solution
Step 1: Understand Angular's default change detection
Angular automatically detects changes for simple data types but can miss changes in complex objects or arrays.Step 2: Role of
ngDoCheckngDoCheckallows developers to add custom checks to detect changes Angular might miss.Final Answer:
To run custom change detection logic when Angular's default detection misses changes. -> Option AQuick Check:
ngDoCheck = custom change detection [OK]
Hint: Remember: ngDoCheck is for custom checks Angular misses [OK]
Common Mistakes:
- Confusing ngDoCheck with ngOnInit or ngOnDestroy
- Thinking ngDoCheck handles user events
- Assuming ngDoCheck replaces Angular's default detection
2. Which of the following is the correct syntax to implement
ngDoCheck in an Angular component?easy
Solution
Step 1: Recognize Angular lifecycle hook syntax
Angular lifecycle hooks are methods inside the component class with no special syntax like arrow functions or function keywords.Step 2: Identify correct method declaration
ngDoCheck() { console.log('Checking changes'); } shows the correct method syntax inside a class:ngDoCheck() { ... }.Final Answer:
ngDoCheck() { console.log('Checking changes'); } -> Option AQuick Check:
ngDoCheck is a class method, not a function expression [OK]
Hint: Use method syntax inside class for lifecycle hooks [OK]
Common Mistakes:
- Using arrow functions for lifecycle hooks
- Adding function keyword inside class
- Using object literal syntax for hooks
3. Consider this Angular component snippet:
What will be logged if
items = [1, 2, 3];
ngDoCheck() {
if (this.items.length !== this.oldLength) {
console.log('Items changed');
this.oldLength = this.items.length;
}
}What will be logged if
items.push(4) is called and Angular runs change detection?medium
Solution
Step 1: Check initialization of
The code usesoldLengththis.oldLengthbut it is never initialized, so it'sundefinedinitially.Step 2: Runtime behavior after
items.push(4)this.items.lengthbecomes 4, and4 !== undefinedistrue, so'Items changed'is logged. No error occurs.Final Answer:
Items changed -> Option DQuick Check:
4 !== undefined -> true, logs [OK]
Hint: Always initialize variables used in ngDoCheck before use [OK]
Common Mistakes:
- Assuming oldLength is automatically defined
- Expecting ngDoCheck to detect changes without setup
- Thinking accessing undefined properties causes runtime errors
4. Given this
Why might
ngDoCheck implementation:ngDoCheck() {
if (this.data !== this.oldData) {
this.processData();
this.oldData = this.data;
}
}Why might
processData() never be called even if data changes internally (like modifying a property inside an object)?medium
Solution
Step 1: Understand object reference comparison
The!==operator checks if two variables point to different objects, not if the content inside objects changed.Step 2: Effect on
IfngDoChecklogicdatais the same object but its properties change,this.data !== this.oldDatais false, soprocessData()is not called.Final Answer:
Because !== compares object references, not internal changes. -> Option BQuick Check:
Object reference check misses internal mutations [OK]
Hint: Use deep checks or immutable objects for internal changes [OK]
Common Mistakes:
- Thinking !== detects internal object changes
- Assuming ngDoCheck runs only once
- Ignoring method existence or variable declaration
5. You want to detect changes inside a nested object
profile in ngDoCheck. Which approach correctly detects changes to any property inside profile without replacing the whole object?hard
Solution
Step 1: Understand limitations of reference checks
Reference checks only detect if the object itself changed, not internal property changes.Step 2: Use deep comparison for nested changes
A deep comparison function compares all nested properties to detect any internal changes.Step 3: Avoid unnecessary object replacement
Replacing the whole object every time is inefficient; deep comparison allows detecting changes without replacement.Final Answer:
Use a deep comparison function inside ngDoCheck to compare profile with a saved copy. -> Option CQuick Check:
Deep compare nested objects for internal changes [OK]
Hint: Deep compare objects to detect internal changes [OK]
Common Mistakes:
- Relying on reference equality for nested objects
- Manually calling detectChanges inside ngDoCheck
- Replacing whole object unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
