detectChanges() from ChangeDetectorRef. What is the immediate effect on the component's view?import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual-detect', template: `<p>{{counter}}</p><button (click)="increment()">Increment</button>` }) export class ManualDetectComponent { counter = 0; constructor(private cdr: ChangeDetectorRef) {} increment() { this.counter++; this.cdr.detectChanges(); } }
Calling detectChanges() triggers Angular to check the component and its children immediately, updating the view to reflect any changes in data bindings.
ApplicationRef.tick() to trigger change detection manually?ApplicationRef.tick() triggers change detection for the entire Angular application immediately, useful in rare cases when you need a full manual check.
detectChanges() inside ngAfterViewInit cause an ExpressionChangedAfterItHasBeenCheckedError?import { Component, ChangeDetectorRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-error-demo', template: `<p>{{message}}</p>` }) export class ErrorDemoComponent implements AfterViewInit { message = 'Initial'; constructor(private cdr: ChangeDetectorRef) {} ngAfterViewInit() { this.message = 'Changed after view init'; this.cdr.detectChanges(); } }
The error occurs because Angular detects that a bound value changed after it finished checking the view, which is not allowed to prevent inconsistent UI.
ChangeDetectorRef and triggers manual change detection in an Angular component method.Option D correctly injects ChangeDetectorRef as a private property and calls detectChanges() on that instance.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-detach-demo', template: `<p>{{counter}}</p><button (click)="increment()">Increment</button>` }) export class DetachDemoComponent { counter = 0; constructor(private cdr: ChangeDetectorRef) { this.cdr.detach(); } increment() { this.counter++; if (this.counter === 2) { this.cdr.reattach(); } } }
Initially, change detection is detached, so the view does not update on the first click (counter=1). After the second click, reattach() is called, so the view updates to show 2.
