Angular Master (283 Qs)•Part 7: Change Detection, Security (XSS/Sanitizer) & Interceptors (151 - 176)
What are the ways to trigger change detection in Angular?
junior LevelMost AskedCode ExampleChange DetectionSecurity & Auth
You can inject either ApplicationRef or NgZone, or ChangeDetectorRef into your component and apply below specific methods to trigger change detection in Angular. i.e, There are 3 possible ways,
- ApplicationRef.tick(): Invoke this method to explicitly process change detection and its side-effects. It check the full component tree.
- NgZone.run(callback): It evaluate the callback function inside the Angular zone.
- ChangeDetectorRef.detectChanges(): It detects only the components and it's children.
Practical Code Example
typescript
// Triggering Change Detection Manually:
import { Component, ChangeDetectorRef, inject } from '@angular/core';
@Component({ selector: 'app-counter', standalone: true, template: '{{ count }}' })
export class CounterComponent {
private cdr = inject(ChangeDetectorRef);
count = 0;
updateManually() {
this.count = 42;
this.cdr.detectChanges(); // Triggers change detection on demand!
}
}