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?
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; } } }
Think about how ngDoCheck lets you write your own logic to detect changes beyond Angular's default checks.
ngDoCheck runs every change detection cycle. It allows you to compare nested properties manually. So even if the object reference stays the same, changes inside can be detected if you write the check.
ngDoCheck called in Angular's lifecycle?Which statement best describes when Angular calls the ngDoCheck lifecycle hook?
Think about how Angular runs change detection frequently to keep the UI updated.
ngDoCheck runs after every change detection cycle, allowing custom checks even if Angular's default checks find no changes.
ngDoCheck implementation cause performance issues?Review this ngDoCheck method. Why might it cause performance problems?
ngDoCheck() {
for (let i = 0; i < 1000000; i++) {
// heavy computation
Math.sqrt(i);
}
console.log('Checked');
}Remember how often Angular runs change detection and calls ngDoCheck.
ngDoCheck runs after every change detection cycle, which can be many times per second. Heavy work inside it slows the app.
ngDoCheck implementationWhich option contains the correct syntax for implementing ngDoCheck in an Angular component?
Remember how methods are declared inside a class in TypeScript.
In Angular components, lifecycle hooks are class methods declared with parentheses and curly braces. Option A is correct syntax.
ngDoCheck?Given this component code, what will be logged to the console after the sequence of changes?
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
Track the value changes carefully and when ngDoCheck logs happen.
After increment(), value is 1, logged. After replaceCounter(), value is 10, logged. After increment(), value is 11, logged.