Bird
Raised Fist0
Angularframework~20 mins

ngDoCheck for custom change detection in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ngDoCheck Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does ngDoCheck affect component updates?

Consider an Angular component that implements ngDoCheck to detect changes in an object property. What happens when the object reference does not change but a nested property is updated?

Angular
export class MyComponent implements DoCheck {
  data = { count: 0 };
  oldCount = 0;

  ngDoCheck() {
    if (this.data.count !== this.oldCount) {
      console.log('Count changed:', this.data.count);
      this.oldCount = this.data.count;
    }
  }
}
AThe console logs 'Count changed:' every time the nested property changes, even if the object reference is the same.
BThe console never logs anything because <code>ngDoCheck</code> only detects reference changes, not nested property changes.
CThe console logs 'Count changed:' only when the object reference changes, not when nested properties change.
DThe console logs 'Count changed:' only once when the component initializes.
Attempts:
2 left
💡 Hint

Think about how ngDoCheck lets you write your own logic to detect changes beyond Angular's default checks.

❓ lifecycle
intermediate
1:30remaining
When is ngDoCheck called in Angular's lifecycle?

Which statement best describes when Angular calls the ngDoCheck lifecycle hook?

A<code>ngDoCheck</code> is called only when the component is destroyed.
B<code>ngDoCheck</code> is called only once after the component is initialized.
C<code>ngDoCheck</code> is called after every change detection cycle, even if no input properties changed.
D<code>ngDoCheck</code> is called only when input properties change.
Attempts:
2 left
💡 Hint

Think about how Angular runs change detection frequently to keep the UI updated.

🔧 Debug
advanced
2:00remaining
Why does this ngDoCheck implementation cause performance issues?

Review this ngDoCheck method. Why might it cause performance problems?

Angular
ngDoCheck() {
  for (let i = 0; i < 1000000; i++) {
    // heavy computation
    Math.sqrt(i);
  }
  console.log('Checked');
}
ABecause <code>ngDoCheck</code> runs only on input changes, the computation is unnecessary.
BBecause <code>ngDoCheck</code> only runs once, the heavy computation is wasted.
CBecause <code>ngDoCheck</code> is asynchronous, the computation blocks UI updates.
DBecause <code>ngDoCheck</code> runs very often, heavy computations inside it slow down the app.
Attempts:
2 left
💡 Hint

Remember how often Angular runs change detection and calls ngDoCheck.

📝 Syntax
advanced
1:30remaining
Identify the syntax error in this ngDoCheck implementation

Which option contains the correct syntax for implementing ngDoCheck in an Angular component?

A
ngDoCheck() {
  console.log('Checking...');
}
B
ngDoCheck {
  console.log('Checking...');
}
C
ngDoCheck() =&gt; {
  console.log('Checking...');
}
D
function ngDoCheck() {
  console.log('Checking...');
}
Attempts:
2 left
💡 Hint

Remember how methods are declared inside a class in TypeScript.

❓ state_output
expert
2:30remaining
What is the console output after these changes with ngDoCheck?

Given this component code, what will be logged to the console after the sequence of changes?

Angular
export class CounterComponent implements DoCheck {
  counter = { value: 0 };
  oldValue = 0;

  ngDoCheck() {
    if (this.counter.value !== this.oldValue) {
      console.log('Counter changed to', this.counter.value);
      this.oldValue = this.counter.value;
    }
  }

  increment() {
    this.counter.value++;
  }

  replaceCounter() {
    this.counter = { value: 10 };
  }
}

// Sequence:
// 1. increment()
// 2. ngDoCheck runs
// 3. replaceCounter()
// 4. ngDoCheck runs
// 5. increment()
// 6. ngDoCheck runs
A
Counter changed to 1
Counter changed to 10
B
Counter changed to 1
Counter changed to 10
Counter changed to 11
C
Counter changed to 1
Counter changed to 11
D
Counter changed to 10
Counter changed to 11
Attempts:
2 left
💡 Hint

Track the value changes carefully and when ngDoCheck logs happen.

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