Sub topic 7
Manual control with ChangeDetectorRef
This chapter assumes you know how an OnPush component is checked: when an input gets a new reference, when an event fires in its template, and when an async pipe or signal notifies Angular. It also assumes you can write basic RxJS subscriptions. Here you will learn what to do when none of those triggers apply, and Angular still needs a hint.
What ChangeDetectorRef is
ChangeDetectorRef is a service that Angular injects for each component. It gives you a handle on that component's view, which is the part of the DOM the component owns. The handle has four methods you will use:
| Method | What it does |
|---|---|
| `markForCheck()` | Flags this view and its ancestors to be checked on the next pass. It does not run a check itself. |
| `detectChanges()` | Runs a check on this view and its children right now. |
| `detach()` | Removes the view from the change detection tree. |
| `reattach()` | Puts a detached view back into the tree. |
markForCheck: tell Angular to look later
Use markForCheck() when a plain field changes outside any trigger. A manual subscription is the usual case.
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DestroyRef,
inject,
OnInit,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Count: {{ count }}</p>`,
})
export class CounterComponent implements OnInit {
count = 0;
private cdr = inject(ChangeDetectorRef);
private destroyRef = inject(DestroyRef);
ngOnInit() {
interval(1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.count++;
this.cdr.markForCheck();
});
}
}Without the markForCheck() call, count would change in memory but the text on screen would stay at 0. With Zone.js, the interval callback does trigger a change detection pass. That pass skips this component, because nothing marked it as dirty.
markForCheck() marks the component and every ancestor up to the root. The ancestors matter because Angular walks the tree from the top. If a parent is OnPush and not marked, Angular never reaches the child.
The sibling is not marked, so an OnPush sibling is still skipped. Calling markForCheck() many times before the next pass costs almost nothing, because it only sets flags.
detectChanges: check right now
detectChanges() runs a check synchronously on the component's view and its children. It does not mark ancestors. Use it when you need the DOM updated immediately, for example before measuring an element's size.
Two common errors come from it:
- Calling it on a destroyed view throws an error. If a subscription can fire after destruction, tie it to
takeUntilDestroyed. - Calling it in a hot loop or on every event wastes the savings OnPush gave you. Prefer
markForCheck()unless you need the result immediately.
detach and reattach: take over scheduling
detach() removes the view from the tree, so Angular's passes skip it. Nothing updates until you call detectChanges() yourself or call reattach(). This is useful when data changes much faster than users can read it.
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DestroyRef,
inject,
OnInit,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval, timer } from 'rxjs';
@Component({
selector: 'app-price-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Price: {{ price }}</p>`,
})
export class PriceTickerComponent implements OnInit {
price = 100;
private cdr = inject(ChangeDetectorRef);
private destroyRef = inject(DestroyRef);
ngOnInit() {
this.cdr.detach();
// The value changes ten times a second.
interval(100)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.price++);
// The screen refreshes once a second.
timer(0, 1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.cdr.detectChanges());
}
}The timer(0, 1000) call fires once immediately, so the first value renders without a one-second wait.
Choosing between the methods
- Start with the async pipe or a signal. Both notify Angular for you.
- If you must subscribe by hand and write to a plain field, call
markForCheck(). - If you need the DOM updated at a specific moment, call
detectChanges(). - If you need to throttle a very busy view, use
detach()with a scheduleddetectChanges().
A frequent mistake is calling detectChanges() where markForCheck() is enough. Another is calling markForCheck() in a place that never runs, such as a subscription that was never subscribed to. When a view stays stale, first confirm the callback runs, then confirm a notification follows the change.
Exercise
A component uses ChangeDetectionStrategy.OnPush and subscribes to an Observable in ngOnInit. The subscribe callback assigns the value to a plain field used in the template, and the screen never updates. Name two ways to fix it and say which one you would pick first.
Show answer
One fix is to call this.cdr.markForCheck() inside the subscribe callback after assigning the field. The other is to remove the manual subscription and bind the Observable in the template with the async pipe, which calls markForCheck for you. Pick the async pipe first, because it also unsubscribes automatically. Use markForCheck when you must keep the manual subscription.