Sometimes Angular does not notice changes automatically. You can tell it to check for changes yourself to update the screen.
0
0
Triggering detection manually in Angular
Introduction
When you update data outside Angular's usual methods, like in a timer or event.
When you want to improve performance by controlling when Angular checks for changes.
When you use third-party libraries that change data but Angular does not detect it.
When you want to refresh the view after a manual data update.
Syntax
Angular
import { ChangeDetectorRef } from '@angular/core'; constructor(private cdr: ChangeDetectorRef) {} someMethod() { // update data this.cdr.detectChanges(); }
You inject ChangeDetectorRef to access manual detection.
Call detectChanges() to tell Angular to update the view immediately.
Examples
This example updates the message after 1 second and manually triggers change detection to update the view.
Angular
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual-detect', template: `<p>{{message}}</p>` }) export class ManualDetectComponent { message = 'Hello'; constructor(private cdr: ChangeDetectorRef) {} updateMessage() { setTimeout(() => { this.message = 'Updated!'; this.cdr.detectChanges(); }, 1000); } }
Here, clicking the button increases count and manually triggers detection to update the number shown.
Angular
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual-detect', template: `<button (click)="update()">Click me</button><p>{{count}}</p>` }) export class ManualDetectComponent { count = 0; constructor(private cdr: ChangeDetectorRef) {} update() { this.count++; this.cdr.detectChanges(); } }
Sample Program
This component counts seconds every second. It updates the seconds variable inside a timer and manually triggers Angular to update the view.
Angular
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-timer-update', template: `<p>Seconds passed: {{seconds}}</p>` }) export class TimerUpdateComponent { seconds = 0; constructor(private cdr: ChangeDetectorRef) { setInterval(() => { this.seconds++; this.cdr.detectChanges(); }, 1000); } }
OutputSuccess
Important Notes
Manual detection is useful but use it carefully to avoid performance issues.
If you forget to call detectChanges(), the view may not update as expected.
Angular usually detects changes automatically, so manual triggering is for special cases.
Summary
You can manually tell Angular to check for changes using ChangeDetectorRef.detectChanges().
This helps when Angular misses updates from outside its normal flow.
Use manual detection to keep your app's view in sync with data changes.