Complete the code to implement the ngDoCheck lifecycle hook in an Angular component.
import { Component, [1] } from '@angular/core'; @Component({ selector: 'app-check', template: `<p>Check example</p>` }) export class CheckComponent implements [1] { ngDoCheck() { console.log('Custom change detection running'); } }
The DoCheck interface allows you to implement the ngDoCheck method for custom change detection.
Complete the code to detect changes manually inside ngDoCheck.
import { Component, DoCheck, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual-check', template: `<p>{{message}}</p>` }) export class ManualCheckComponent implements DoCheck { message = 'Initial'; constructor(private cdr: [1]) {} ngDoCheck() { this.message = 'Checked'; this.cdr.detectChanges(); } }
The ChangeDetectorRef service allows manual triggering of change detection.
Fix the error in the ngDoCheck method to avoid infinite loops.
ngDoCheck() {
if (this.value !== this.previousValue) {
this.previousValue = this.value;
this.message = 'Value changed';
[1];
}
}Using markForCheck() schedules change detection without causing an immediate cycle, preventing infinite loops.
Fill both blanks to create a custom change detection that compares old and new values.
export class CustomCheckComponent implements DoCheck { oldValue = ''; newValue = 'Hello'; ngDoCheck() { if (this.newValue [1] this.oldValue) { this.oldValue = this.newValue; console.log('Value changed:', this.newValue); } } }
The strict inequality operator !== checks if values are different, triggering the change logic.
Fill all three blanks to implement ngDoCheck with manual change detection and previous value tracking.
export class TrackValueComponent implements DoCheck { previousValue = ''; currentValue = 'Angular'; constructor(private [1]: ChangeDetectorRef) {} ngDoCheck() { if (this.currentValue [2] this.previousValue) { this.previousValue = this.currentValue; this.[3].markForCheck(); } } }
Inject ChangeDetectorRef as cdr, compare values with !==, and call cdr.markForCheck() to schedule change detection.