Sub topic 7
Manual control with ChangeDetectorRef
An OnPush component refreshes only when Angular has a reason to check it. Input reference changes, events from its template and signal reads in the template all give that reason automatically. Some updates give none, such as a plain field changed in a manual subscription or a callback from a third-party library. ChangeDetectorRef is the API you use to tell Angular about those updates, or to take over scheduling for a component.
Prerequisites
This chapter assumes you already know:
- How OnPush decides whether to check a component, covered in the earlier chapters on the strategy and its triggers.
- How to subscribe to an RxJS Observable and unsubscribe from it.
- How to inject a service with
inject().
What ChangeDetectorRef is
ChangeDetectorRef is a class you inject into a component. The injected instance controls the change detection of that component's own view. For a component, this means its template and the child components inside it.
private cdr = inject(ChangeDetectorRef);It has four methods you will use in practice.
| Method | What it does | Runs a check now? |
|---|---|---|
| `markForCheck()` | Marks this component and all its ancestors up to the root as needing a check on the next pass | No |
| `detectChanges()` | Checks this component's view and its children synchronously | Yes, for this subtree only |
| `detach()` | Removes the view from the change detection tree | No |
| `reattach()` | Puts a detached view back into the tree | No |
A fifth method, checkNoChanges(), runs the development-mode check that raises ExpressionChangedAfterItHasBeenCheckedError. You will rarely call it yourself.
markForCheck: schedule a check
markForCheck() does not check anything. It sets a "dirty" flag on the component's view and on every ancestor view up to the root. The next change detection pass then walks down from the root. Normally an OnPush component that is not dirty is skipped, along with its subtree. A dirty one is checked, and so are the ancestors that lead to it.
The flag is needed on the ancestors because the walk starts at the root. If an ancestor were skipped, Angular would never reach your component.
Here is the manual-subscription case from the spine.
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();
});
}
}The interval callback changes count, but nothing in OnPush's trigger list fires. No input changed, no template event happened and count is not a signal. Without markForCheck() the field would change while the screen kept showing 0. In an app that uses Zone.js, the timer does cause a change detection pass. The pass would just skip this component, because it is not dirty. markForCheck() makes the pass include it.
When to call it
- After a plain field changes inside a manual
subscribecallback. - After a callback from a library that Angular does not know about, such as a map widget or a WebSocket wrapper.
- After a
Promise.thenorsetTimeoutthat updates a field.
Call it after the state change, in the same callback. Calling it many times in one tick is cheap, because it only sets flags. Several calls in the same tick produce a single check.
Why you often do not need it
If the value flows through the async pipe, the pipe calls markForCheck() for you each time the Observable emits. A signal read in the template does the same job. Reach for markForCheck() only when your data lives in a plain field. If you find yourself adding it to many components, consider moving that state into signals or into Observables rendered with async.
detectChanges: check now, locally
detectChanges() runs change detection synchronously on this component's view and its children. It does not go through ancestors and does not wait for the next application pass.
import { ChangeDetectorRef, Component, inject } from '@angular/core';
@Component({
selector: 'app-progress',
template: `<p>Progress: {{ percent }}%</p>`,
})
export class ProgressComponent {
percent = 0;
private cdr = inject(ChangeDetectorRef);
setPercent(value: number) {
this.percent = value;
// Render immediately, then continue with the code below.
this.cdr.detectChanges();
console.log('DOM now shows', value);
}
}Use it when you need the DOM to be up to date at a specific line, for example before measuring an element's size. It is also the tool for a detached view, covered next.
It has costs you should know about:
- It runs a check even if the view is not dirty. It is the one method here that bypasses OnPush's own filtering for this view.
- It does not update ancestors. If a parent template displays something derived from this component's state, the parent stays stale.
- Calling it inside a lifecycle hook or template binding that is already part of a running check can cause recursion or
ExpressionChangedAfterItHasBeenCheckederrors. - Calling it on a destroyed view throws an error. An async callback that fires after the component is destroyed is the usual cause. Tie subscriptions to
takeUntilDestroyedso they stop first.
In a normal OnPush component, prefer markForCheck(). It lets Angular batch the work into one pass. detectChanges() makes you responsible for when rendering happens.
detach and reattach
detach() takes the component's view out of the change detection tree. Nothing checks it during an application pass, whatever its strategy and whether or not it is dirty. Calling markForCheck() on a detached view does not make it render. The view is checked again only after reattach(), or when you call detectChanges() on it directly.
The classic use is rate limiting a component that receives data much faster than a human can read it.
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DestroyRef,
inject,
OnInit,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-price-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Price: {{ price.toFixed(2) }}</p>`,
})
export class PriceTickerComponent implements OnInit {
price = 0;
private cdr = inject(ChangeDetectorRef);
private destroyRef = inject(DestroyRef);
ngOnInit() {
// Take over scheduling for this view.
this.cdr.detach();
this.cdr.detectChanges(); // first render
// Data arrives 10 times per second.
interval(100)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.price = Math.random() * 100;
});
// The screen refreshes once per second.
interval(1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.cdr.detectChanges());
}
}The 100 ms timer only writes a field, and the view is not touched. The 1000 ms timer renders it. The component displays one frame per second, however fast the data arrives.
Detaching has real costs:
- Every update becomes your job. Forget one
detectChanges()call and the view is stale. - Child components inside the detached view are not refreshed by application passes either, including their input updates.
detectChanges()on a detached view still works. Treat that as the intended way to render it.
Because of those costs, detaching is a last resort for measured performance problems. Cheaper options usually come first: throttle the Observable with RxJS and use the async pipe, or use a signal that updates once per second.
Choosing between the methods
The decision usually comes down to three questions.
- Does a template-visible value change through a path Angular already tracks (input, template event, signal,
asyncpipe)? If so, call nothing. - Does it change in a plain field from your own callback? Call
markForCheck()after the change. - Do you need the DOM updated at this exact moment, or do you control the refresh rate yourself? Use
detectChanges(), and considerdetach()if you are throttling.
A common refactor removes the manual calls altogether. Compare the counter above with the signal version, which needs neither markForCheck() nor detectChanges().
import { ChangeDetectionStrategy, Component, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-counter-signal',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Count: {{ count() }}</p>`,
})
export class CounterSignalComponent implements OnInit {
count = signal(0);
private destroyRef = inject(DestroyRef);
ngOnInit() {
interval(1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.count.update((c) => c + 1));
}
}Common errors
Calling markForCheck before the change. The call only sets flags, so the order within one synchronous callback does not matter much. It matters across async boundaries. If you call it and then update the field in a later setTimeout, the update is not marked.
Expecting markForCheck to render immediately. It schedules. If code on the next line reads the DOM, it sees the old value. Use detectChanges() for that.
Marking a component that is outside Angular's awareness. In an app with Zone.js, code run through NgZone.runOutsideAngular() triggers no pass. In older versions, markForCheck() alone did not start one, so the flag waited until something else caused a pass. Recent versions have a scheduler that also notices markForCheck(), but do not depend on that. If you run code outside the zone, re-enter it with NgZone.run() when the screen needs an update, or use a signal.
Using detectChanges on a destroyed component. This throws. Cancel the subscription or timer when the component is destroyed.
Detaching and forgetting. A detached view silently ignores input changes and events. If a component stops updating and the code contains detach(), check that first.
Using these calls to hide a mutation bug. If a parent mutates an object and the child is stale, the fix is an immutable update in the parent. Calling markForCheck() in the child works only where you remembered to add it, and it hides the real problem.
Summary of behavior
markForCheck()marks the view and its ancestors and renders later, in the next pass.detectChanges()renders this subtree now and leaves ancestors alone.detach()removes the view from passes untilreattach(). OnlydetectChanges()renders it in the meantime.- Prefer
asyncand signals. UseChangeDetectorReffor values that live outside both.
Exercise
A component uses OnPush and subscribes manually to a service in ngOnInit. The callback assigns this.items = data;. The list never updates on screen, although a console.log in the callback shows new data. Name the cause and give two ways to fix it.
Show answer
Assigning a plain field in a manual subscription is not an OnPush trigger, so Angular never marks the component dirty and the pass skips it. Fix 1: inject ChangeDetectorRef and call this.cdr.markForCheck() after the assignment. Fix 2: avoid the manual subscription by exposing the Observable and rendering it with the async pipe, or store the data in a signal (items = signal<Item[]>([]) and this.items.set(data)) and read items() in the template.
Exercise
In the PriceTickerComponent above, what would you see on screen if you removed the line this.cdr.detectChanges(); inside the one-second interval, and why does calling markForCheck() there not help?
Show answer
The view would stay at its first render and never update. Once detach() is called, the view is out of the change detection tree, so application passes skip it even when it is marked dirty. Only detectChanges() (or reattach() followed by a pass) renders a detached view.
Exercise
What is the difference in scope between markForCheck() and detectChanges()?
Show answer
markForCheck() marks the component and all its ancestors as dirty and renders nothing by itself; the check happens in the next application pass, which walks down from the root. detectChanges() checks only the component's own view and its children immediately and synchronously, and it does not touch ancestors.