Back to results for “Dependency Injection”
Angular › Change Detection

How would you manually trigger change detection in Angular when needed, such as after code that runs outside Angular's normal tracking?

Intermediate

Answer

You can inject the ChangeDetectorRef service and call its detectChanges or markForCheck method to tell Angular to check a specific component, which is sometimes necessary when a value changes as a result of code Angular does not automatically know about, such as a third party library callback.
import { ChangeDetectorRef } from '@angular/core';

constructor(private cdr: ChangeDetectorRef) {}

onThirdPartyCallback(newValue: string) {
  this.value = newValue;
  this.cdr.detectChanges(); // manually tell Angular to check this component now
}
Real-world example A component integrating a third party mapping library manually calls detectChanges after the library's callback updates a value, ensuring the page correctly reflects the change even though Angular could not automatically detect it on its own.

Common follow-ups: What is the difference between detectChanges and markForCheck?;Why should manually triggering change detection generally be a last resort rather than a common pattern?