Sub topic 8
Controlling checks with ChangeDetectorRef
This chapter assumes you know how OnPush components decide when to run, and that you have used setTimeout, promises, and component inputs. Here you will learn how to use ChangeDetectorRef when an OnPush component needs a check that Angular would not schedule on its own.
What ChangeDetectorRef is
ChangeDetectorRef is a service tied to one component's view. You get it with inject(ChangeDetectorRef). It lets your code tell Angular about that view: mark it as needing a check, check it right now, or take it out of the tree.
The three methods you will use most are in this table.
| Method | What it does | When to use it |
|---|---|---|
| `markForCheck()` | Marks this component and all its ancestors as dirty. Angular checks them on the next cycle. | State changed in a place Angular does not watch. |
| `detectChanges()` | Runs a check on this component and its children immediately. | You need the DOM updated right now. |
| `detach()` / `reattach()` | Removes the view from the check, or puts it back. | Rare, for views that should be frozen for a while. |
Why OnPush sometimes needs help
An OnPush component is checked only when an input reference changes, an event fires in its template, it is marked dirty, or a signal read in its template changes. A setInterval callback inside the class matches none of these. Zone.js still starts a cycle after the timer fires, but Angular skips the OnPush component because nothing marked it dirty. The class field changes and the screen stays the same.
markForCheck
markForCheck() solves this. It does not run a check. It sets a dirty flag on the component and on every ancestor up to the root, so the next cycle reaches the component.
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject } from '@angular/core';
@Component({
selector: 'app-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds: {{ count }}</p>`,
})
export class Ticker {
private cdr = inject(ChangeDetectorRef);
count = 0;
constructor() {
setInterval(() => {
this.count++;
this.cdr.markForCheck();
}, 1000);
}
}Each tick increments count, marks the view, and Zone.js triggers a cycle, which now includes Ticker. Without the markForCheck() call, the counter would stay at 0 on screen.
Ancestors are marked too because Angular walks the tree from the root. If a parent were skipped, the walk would never reach the child.
detectChanges
detectChanges() runs the check synchronously for this component and its children. Use it when you must read the updated DOM on the next line, or when a view is detached. It does not mark ancestors, and it checks only the subtree below the component.
import { ChangeDetectorRef, Component, ElementRef, inject, viewChild } from '@angular/core';
@Component({
selector: 'app-message',
template: `<p #text>{{ message }}</p>`,
})
export class Message {
private cdr = inject(ChangeDetectorRef);
private text = viewChild.required<ElementRef<HTMLParagraphElement>>('text');
message = '';
show(value: string) {
this.message = value;
this.cdr.detectChanges();
console.log(this.text().nativeElement.textContent); // already shows the new value
}
}Calling detectChanges() often is a design smell. It forces extra work that the normal cycle would have done anyway. Do not call it inside a lifecycle hook that runs during a check, such as ngAfterViewChecked, because it can loop.
detach and reattach
detach() removes the view from the normal tree walk. The component stays on screen but is never updated until you call detectChanges() yourself or reattach(). This is rare in application code. It suits a heavy view you want to refresh on your own schedule.
Choosing between them
- Prefer signals or the async pipe, because they mark the view for you.
- Use
markForCheck()when state changes in a callback Angular cannot see, such as a timer or a third-party library. - Use
detectChanges()only when you need the DOM updated immediately. - Avoid
detach()unless profiling shows a clear need.
Exercise
Exercise
An OnPush component updates a field inside a setTimeout callback, but the template never shows the new value. Which call fixes it, and why do ancestors also get marked?
Show answer
Call markForCheck() on the component's ChangeDetectorRef after changing the field. It sets the dirty flag on the component and all its ancestors, because Angular checks the tree from the root downward and must pass through every ancestor to reach the component. Zone.js already starts the cycle after the timer fires.