Sub topic 8
Controlling checks with ChangeDetectorRef
This chapter assumes you know Angular components, templates, and the difference between the Default and OnPush strategies. It also assumes you know that Zone.js starts a change detection cycle after asynchronous work finishes. Here you will learn what ChangeDetectorRef offers, when each method is the right tool, and which mistakes show up most often.
What ChangeDetectorRef is
ChangeDetectorRef is a service that gives a component (or directive) a handle on its own view. You get it with inject(ChangeDetectorRef). Each component receives its own instance, tied to that component's view.
The class has four methods that matter in everyday code:
| Method | What it does | Runs a check now? |
|---|---|---|
| `markForCheck()` | Marks this view and all its ancestors as dirty, so the next cycle checks them | No |
| `detectChanges()` | Checks this view and its children right away | Yes, synchronously |
| `detach()` | Removes this view from the change detection tree | No |
| `reattach()` | Puts a detached view back into the tree | No |
The first two methods are the common ones. The other two are specialised and are covered near the end.
Why OnPush needs help
An OnPush component is checked only in these cases:
- An input reference changed.
- An event fired from its template.
- A signal read in its template changed.
- The component was marked dirty.
Anything else, such as a setTimeout, a manual subscription, or a promise callback, can change a field without any of those four things happening. Zone.js still starts a cycle, but Angular walks past the OnPush component because it is not dirty. The field has a new value and the screen shows the old one.
markForCheck() is the way to mark the component dirty yourself.
markForCheck: mark dirty, check later
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 cycle then reaches the component, because each ancestor on the path is also flagged.
The ancestors need the flag because Angular walks from the root downward. If a parent is an OnPush component that is not dirty, Angular skips its whole subtree and never reaches the child. Marking the full path to the root keeps the walk from stopping early.
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 timer tick changes count. Zone.js notices that the timer callback finished and schedules a cycle. Without markForCheck() that cycle would skip Ticker. With it, Ticker and its ancestors are flagged, and the cycle updates the text.
Two properties of markForCheck() are worth remembering:
- It is cheap and safe to call several times. Ten calls before the next cycle give the same result as one.
- It does nothing by itself. If no cycle runs afterwards, the view is not updated. In a zone-based app something almost always triggers a cycle, but in a zoneless app the call is itself one of the things that schedules a cycle (see the zoneless chapter).
The dirty flag is cleared after the component has been checked, so you must call markForCheck() again after the next out-of-band change.
The diagram below shows the path that markForCheck() marks.
Sidebar is not on the path from Ticker to the root, so an OnPush Sidebar is still skipped. That is the point of the design: only the path that needs the update pays for it.
detectChanges: check right now
detectChanges() runs change detection for this view and its children immediately, before the call returns. It does not mark ancestors, and it does not wait for the next cycle.
import { ChangeDetectorRef, Component, inject } from '@angular/core';
@Component({
selector: 'app-report',
template: `<p>{{ status }}</p>`,
})
export class Report {
private cdr = inject(ChangeDetectorRef);
status = 'Idle';
run() {
this.status = 'Working';
this.cdr.detectChanges(); // the DOM shows "Working" before the heavy loop starts
for (let i = 0; i < 5e8; i++) {
// blocking work
}
this.status = 'Done';
}
}In this example detectChanges() forces the text to update before a long synchronous loop. Without it the browser would not repaint until the loop ends, and the user would never see "Working". The final status = 'Done' is picked up by the normal cycle that follows the event handler.
Compare the two main methods:
| Aspect | `markForCheck()` | `detectChanges()` |
|---|---|---|
| Timing | Next cycle | Immediately |
| Scope | This view and all ancestors are flagged | This view and its children only |
| Cost | Very low | One full check of the subtree per call |
| Typical use | OnPush component changed outside Angular's knowledge | Force a DOM update at a precise moment |
Gotchas with detectChanges
- Repeated calls are expensive. Every call checks the whole subtree under the component. Calling it inside a loop or a high-frequency callback can cost more than the Default strategy you were trying to avoid.
- It is not allowed on a destroyed view. Calling
detectChanges()after the component has been destroyed throws an error. This often happens in a callback from a subscription that was never cancelled. Unsubscribe inngOnDestroy, or usetakeUntilDestroyed(). - It does not fix the parent. If an OnPush ancestor is not dirty, the parent view is still skipped on the next cycle.
detectChanges()updates only this component and its children. That is fine when the change affects only this component's template. - It can hide design problems. If you need
detectChanges()in many places, the state probably should live in signals, or flow through inputs or the async pipe.
Choosing between them
Use this order of preference for an OnPush component whose state changes from code Angular does not track:
- Put the state in a signal and read it in the template. Nothing else is needed.
- Use the async pipe for observables.
- Call
markForCheck()after assigning plain fields. - Call
detectChanges()only when you need the DOM updated at an exact point, such as before measuring an element.
The first two options are covered in the next chapters. markForCheck() is the fallback for code that still uses plain fields and manual subscriptions.
detach and reattach
detach() removes the view from the change detection tree. Angular then skips it, and its children, on every cycle until you call reattach(). The component still works, and its event listeners still fire, but its template bindings are no longer refreshed by the normal cycle.
You can combine detach() with detectChanges() to take full manual control:
import { ChangeDetectorRef, Component, inject, OnInit } from '@angular/core';
@Component({
selector: 'app-live-feed',
template: `<p>Latest value: {{ latest }}</p>`,
})
export class LiveFeed implements OnInit {
private cdr = inject(ChangeDetectorRef);
latest = 0;
ngOnInit() {
this.cdr.detach();
setInterval(() => {
this.latest = Math.random();
this.cdr.detectChanges(); // only this view refreshes, and only once a second
}, 1000);
}
}Be careful with this pattern:
- A detached view is not updated by any other trigger, including inputs changing and events from its own template. You must call
detectChanges()whenever the view needs to change. - The first render still needs to happen. In the example above the initial check runs before
ngOnInit, so the first value is shown. If you detach in the constructor, the view may never be rendered until you calldetectChanges(). - Forgetting
reattach()ordetectChanges()produces a component that looks frozen. This is hard to debug because nothing throws. - In most cases OnPush plus
markForCheck()or signals gives the same savings with less risk. Reservedetach()for views with very high update rates, where you decide exactly when to draw.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Value changes in code but the screen stays old, with OnPush | Field changed in a timer, subscription or promise without marking | Call `markForCheck()`, or use a signal or async pipe |
| `ExpressionChangedAfterItHasBeenCheckedError` after adding `detectChanges()` | Calling it in a hook or setter during a check, so the state changes after the parent was checked | Move the state change earlier, or into a signal |
| Error about a destroyed view | `detectChanges()` called from a callback that outlived the component | Cancel the subscription or timer on destroy |
| Component looks frozen | View was detached and never refreshed | Call `detectChanges()` after changes, or `reattach()` |
| Slow screen after "fixing" with `detectChanges()` | Called on every event in a hot path | Use `markForCheck()` and let Angular batch the work |
Summary of the model
markForCheck()says "check me on the next cycle", and it flags the ancestors so the walk can reach this component.detectChanges()says "check me now", and it covers this view and its children.detach()andreattach()remove and restore a view in the tree, and they are an advanced tool.- None of these methods is needed when state flows through inputs, signals or the async pipe.
Exercise
An OnPush component Clock assigns this.time = new Date() inside a setInterval callback, and its template shows {{ time | date:'mediumTime' }}. The value on screen never changes. Explain why, and give the smallest fix. Then say what would go wrong if you replaced your fix with detectChanges() and the component was destroyed while the interval was still running.
Show answer
The interval callback runs, and Zone.js triggers a cycle, but Clock is OnPush and is not dirty. No input changed, no template event fired, and no signal changed, so Angular skips it and the DOM keeps the old text. The smallest fix is to inject ChangeDetectorRef and call markForCheck() after assigning this.time. With detectChanges(), a callback that fires after destruction would call it on a destroyed view and throw an error. The interval should also be cleared in ngOnDestroy.
Exercise
A parent is OnPush and has a child that calls markForCheck(). Why does Angular mark the ancestors as well as the child, and what would happen if it marked only the child?
Show answer
Change detection walks from the root downward. If the parent were not dirty, Angular would skip its whole subtree and never reach the child, so the child's dirty flag would have no effect. Marking every ancestor up to the root makes sure the walk reaches the child. Siblings off that path are not marked, so they are still skipped.