Bird
Raised Fist0
Angularframework~10 mins

ngDoCheck for custom change detection in Angular - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - ngDoCheck for custom change detection
Component Initialized
↓
Angular Change Detection Cycle
↓
Call ngDoCheck()
↓
Custom Checks Run
↓
Detect Changes?
Yes→Update View
↓
Cycle Ends
Angular runs its change detection cycle and calls ngDoCheck() where you can add your own checks to detect changes and update the view if needed.
Execution Sample
Angular
import { DoCheck } from '@angular/core';

export class MyComponent implements DoCheck {
  oldValue = '';
  value = '';
  ngDoCheck() {
    if (this.value !== this.oldValue) {
      this.oldValue = this.value;
      console.log('Value changed:', this.value);
    }
  }
}
This component uses ngDoCheck to detect when 'value' changes and logs the change.
Execution Table
StepvalueoldValueCondition (value !== oldValue)ActionOutput
1 (Init)''''FalseNo action
2 (Change value to 'A')'A'''TrueoldValue = 'A'; log changeValue changed: A
3 (Change detection cycle)'A''A'FalseNo action
4 (Change value to 'B')'B''A'TrueoldValue = 'B'; log changeValue changed: B
5 (Change detection cycle)'B''B'FalseNo action
6 (No change)'B''B'FalseNo action
💡 No further changes detected; ngDoCheck ends without updates.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
value'''A''B''B'
oldValue'''A''B''B'
Key Moments - 2 Insights
Why does ngDoCheck run even when the value hasn't changed?
ngDoCheck is called every Angular change detection cycle (see steps 3,5,6) to allow custom checks, but your condition inside ngDoCheck controls if any action happens.
What happens if you forget to update oldValue inside ngDoCheck?
If oldValue is not updated (see step 2 vs step 4), the condition will always be true and ngDoCheck will log changes repeatedly, causing unnecessary updates.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is oldValue after step 4?
A'B'
B''
C'A'
D'C'
💡 Hint
Check the 'oldValue' column in the execution_table at step 4.
At which step does the condition (value !== oldValue) become false after a change?
AStep 4
BStep 2
CStep 3
DStep 6
💡 Hint
Look at the 'Condition' column after step 2 and step 3 in the execution_table.
If you set value to 'C' at step 5, what will happen in the next ngDoCheck call?
ANo action, condition false
BoldValue updates to 'C' and logs change
CError because oldValue is not updated
DngDoCheck stops running
💡 Hint
Refer to how ngDoCheck updates oldValue and logs changes when condition is true in the execution_table.
Concept Snapshot
ngDoCheck is a lifecycle hook Angular calls every change detection cycle.
Use it to run custom change detection logic.
Inside ngDoCheck, compare current and previous values.
If changed, update old values and trigger needed actions.
Helps detect changes Angular's default detection misses.
Full Transcript
This example shows how Angular calls ngDoCheck every change detection cycle. The component tracks a value and an oldValue. When value changes, ngDoCheck detects it by comparing value and oldValue. If different, it updates oldValue and logs the change. If not, it does nothing. This way, you can add your own checks beyond Angular's default detection. The execution table shows each step: initialization, value changes, and detection cycles. The variable tracker shows how value and oldValue update over time. Key moments clarify why ngDoCheck runs often and why updating oldValue is important. The quiz tests understanding of variable states and condition results during the cycle.

Practice

(1/5)
1. What is the main purpose of the ngDoCheck lifecycle hook in Angular?
easy
A. To run custom change detection logic when Angular's default detection misses changes.
B. To initialize component data before rendering.
C. To handle user input events like clicks and keypresses.
D. To destroy the component and clean up resources.

Solution

  1. 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.
  2. Step 2: Role of ngDoCheck

    ngDoCheck allows developers to add custom checks to detect changes Angular might miss.
  3. Final Answer:

    To run custom change detection logic when Angular's default detection misses changes. -> Option A
  4. Quick 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
A. ngDoCheck() { console.log('Checking changes'); }
B. ngDoCheck: function() { console.log('Checking changes'); }
C. function ngDoCheck() { console.log('Checking changes'); }
D. ngDoCheck => { console.log('Checking changes'); }

Solution

  1. 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.
  2. Step 2: Identify correct method declaration

    ngDoCheck() { console.log('Checking changes'); } shows the correct method syntax inside a class: ngDoCheck() { ... }.
  3. Final Answer:

    ngDoCheck() { console.log('Checking changes'); } -> Option A
  4. Quick 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:
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
A. Error: oldLength is undefined
B. Nothing is logged
C. Items changed twice
D. Items changed

Solution

  1. Step 1: Check initialization of oldLength

    The code uses this.oldLength but it is never initialized, so it's undefined initially.
  2. Step 2: Runtime behavior after items.push(4)

    this.items.length becomes 4, and 4 !== undefined is true, so 'Items changed' is logged. No error occurs.
  3. Final Answer:

    Items changed -> Option D
  4. Quick 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 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
A. Because ngDoCheck only runs once per component.
B. Because !== compares object references, not internal changes.
C. Because processData() is not a valid method.
D. Because oldData is not declared.

Solution

  1. Step 1: Understand object reference comparison

    The !== operator checks if two variables point to different objects, not if the content inside objects changed.
  2. Step 2: Effect on ngDoCheck logic

    If data is the same object but its properties change, this.data !== this.oldData is false, so processData() is not called.
  3. Final Answer:

    Because !== compares object references, not internal changes. -> Option B
  4. Quick 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
A. Call detectChanges() manually inside ngDoCheck.
B. Only check if profile !== oldProfile using reference equality.
C. Use a deep comparison function inside ngDoCheck to compare profile with a saved copy.
D. Replace profile with a new object every time a property changes.

Solution

  1. Step 1: Understand limitations of reference checks

    Reference checks only detect if the object itself changed, not internal property changes.
  2. Step 2: Use deep comparison for nested changes

    A deep comparison function compares all nested properties to detect any internal changes.
  3. Step 3: Avoid unnecessary object replacement

    Replacing the whole object every time is inefficient; deep comparison allows detecting changes without replacement.
  4. Final Answer:

    Use a deep comparison function inside ngDoCheck to compare profile with a saved copy. -> Option C
  5. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard