Sub topic 9
Stale views: common mistakes and how to debug them
This chapter assumes you can build components with templates and bindings, use inputs and outputs, and subscribe to RxJS Observables. It also assumes you know the difference between mutating an object and replacing it with a copy. You should know the triggers from earlier chapters: a new input reference, an event inside the component, the async pipe, markForCheck, and a signal read in the template.
A stale view is a template that shows old data after the underlying data has changed. With OnPush, this almost always means Angular was never told the component needed checking. The data is usually correct, and only the screen is behind.
The core question
Every stale-view bug comes down to one question: did anything mark this component, or an ancestor, for checking after the data changed?
Zone.js still runs a change detection pass after most asynchronous work, such as timers, promises and HTTP responses. An OnPush component is skipped during that pass unless it is marked dirty. So the pass happens, but your component doesn't take part in it.
Mistake 1: mutating an input
This is the most common cause. The parent changes an array or object in place, so the reference the child compares against stays the same.
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
@Component({
selector: 'app-todo-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (todo of todos; track $index) {
<li>{{ todo }}</li>
}
</ul>
`,
})
export class TodoListComponent {
@Input({ required: true }) todos!: string[];
}
@Component({
selector: 'app-todo-page',
imports: [TodoListComponent],
template: `
<app-todo-list [todos]="todos" />
<button (click)="addByMutation()">Push</button>
<button (click)="addImmutably()">Copy</button>
`,
})
export class TodoPageComponent {
todos: string[] = ['Write tests'];
addByMutation() {
// Same array reference: the child does not update.
this.todos.push('Review PR');
}
addImmutably() {
// New array reference: the child is checked.
this.todos = [...this.todos, 'Review PR'];
}
}The click handler runs inside the parent's template, so the parent is checked. Angular then compares todos with its previous value using Object.is. The values are identical, so the child's input does not change and the child stays clean.
Mutation bugs also hide in less obvious places:
array.sort(),reverse()andsplice()all mutate in place. UsetoSorted(),toReversed()andtoSpliced(), or copy first with[...list].sort().- Assigning a nested field, as in
this.user.address.city = 'Oslo', changes nothing the child can see. Copy each level that changed:{ ...user, address: { ...user.address, city: 'Oslo' } }. - A service that hands out the same object on every call and edits it in place breaks every OnPush consumer at once.
Mistake 2: updating a field outside the template
A component can change its own plain field in code that Angular does not associate with the template. A setTimeout callback, a manual subscribe, a WebSocket handler and a Promise then are all examples. None of these marks the component dirty.
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
@Component({
selector: 'app-status',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Status: {{ status }}</p>`,
})
export class StatusComponent implements OnInit {
status = 'loading';
ngOnInit() {
setTimeout(() => {
// Zone.js runs a pass after this callback, but this component is not dirty.
this.status = 'ready';
}, 1000);
}
}The field changes, but the screen keeps showing loading. Under Default change detection this would work, which makes the bug confusing when you first move a component to OnPush.
You have three fixes, in order of preference:
- Hold the value in a signal and read it in the template.
- Expose an Observable and bind it with the async pipe.
- Keep the plain field and call
markForCheck()after changing it.
import { ChangeDetectionStrategy, Component, OnInit, signal } from '@angular/core';
@Component({
selector: 'app-status',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Status: {{ status() }}</p>`,
})
export class StatusComponent implements OnInit {
status = signal('loading');
ngOnInit() {
setTimeout(() => this.status.set('ready'), 1000);
}
}Mistake 3: mutating the value inside a signal
A signal notifies its readers only when it is set to a value that is not equal to the old one. By default, equality is Object.is. Pushing into an array held by a signal is the same bug as Mistake 1.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-tags',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>{{ tags().join(', ') }}</p>
<button (click)="addWrong()">Mutate</button>
<button (click)="addRight()">Replace</button>
`,
})
export class TagsComponent {
tags = signal<string[]>(['angular']);
addWrong() {
// The signal never learns anything changed.
this.tags().push('onpush');
}
addRight() {
this.tags.update((list) => [...list, 'onpush']);
}
}The mutating button looks like it does nothing. If you click it and then click the replacing button, both new values appear at once, because the second click finally produced a new reference.
Mistake 4: forgetting that ancestors matter
Angular walks the component tree from the root. If an OnPush ancestor is not dirty, Angular skips its whole subtree, including descendants that are dirty or use Default.
markForCheck() handles this for you. It marks the current component and every ancestor up to the root. Two things follow from that:
- If you call
detectChanges()on a child instead, you refresh only that child's subtree. A parent that renders data derived from the same change stays stale. - If you
detach()a component's change detector, the component and its subtree are not updated until you callreattach(). A detached view that "works in one place and not another" is usually a leftoverdetach().
Events work in the opposite direction. A listener in a template, such as (click) or an @Output handler like (saved)="onSaved()", marks the component that owns the listener and its ancestors. If a child emits an output and the parent's handler changes parent state, the parent is refreshed. A third component elsewhere in the tree is not.
Mistake 5: subscribing manually and forgetting to notify
A manual subscribe() that writes to a field needs markForCheck() on the same line as the write. Forgetting it leaves the view stale until something else dirties the component, so the bug appears intermittent. A click elsewhere in the component refreshes the view and makes the missing update appear.
The async pipe and signals avoid this class of bug. They also unsubscribe for you (the pipe) or have no subscription at all (signals). Prefer them when you can, and reserve manual subscriptions with markForCheck() for cases that need side effects.
A symptom table
| Symptom | Likely cause | Fix |
|---|---|---|
| Child ignores parent changes, but a new object appears after an unrelated click | Input mutated in place | Replace with a copy |
| Field changes in a timer or subscription, and the view never updates | No notification | Signal, async pipe, or `markForCheck()` |
| View updates only after clicking something else in the component | Missing `markForCheck()` after an async write | Notify at the write site |
| Signal-backed list does not change when you push | Signal value mutated | Use `set` or `update` with a new array |
| Test updates a property but the DOM keeps the old text | Direct property write on an OnPush fixture | Use `fixture.componentRef.setInput(...)` |
| View stops updating entirely | `detach()` without `reattach()` | Reattach, or remove the detach |
Debugging techniques
Switch to Default as an experiment
Change the strategy to ChangeDetectionStrategy.Default for a minute. If the view now updates, the data flow is fine and you have a notification problem. If it still does not update, the bug is elsewhere. Look for a wrong binding, an exception in the console, or a request that never returned.
Trace when the template is evaluated
A method call in the template runs every time Angular re-evaluates that binding. A temporary trace shows you when the component is actually checked.
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ trace() }}{{ user.name }}</p>`,
})
export class UserCardComponent {
@Input({ required: true }) user!: { name: string };
trace() {
console.log('UserCard template evaluated');
return '';
}
}Remove the trace afterwards, because it adds work to every check. Do not rely on ngDoCheck for this purpose. It runs whenever the parent's view is checked, even when the OnPush component's own template is skipped.
Force a check from the browser console
In a development build, select the component in the Elements panel and run this in the console:
ng.applyChanges(ng.getComponent($0))$0 is the selected element in browser dev tools. The call marks the component dirty and runs change detection. If the view then shows the right data, the data was correct and the only problem was a missing notification.
Compare references
When you suspect mutation, keep the previous value and compare it. In the parent, console.log(previous === this.todos) after the update tells you directly whether the reference changed. In the child, ngOnChanges fires only when Angular sees a changed input. If it does not fire after the parent updates, the reference did not change.
Use Angular DevTools
The Angular DevTools profiler records each change detection pass and shows which components were checked. A component that never appears in a pass after your data change was never marked dirty.
Avoid these shortcuts
Stale views in tests
The same rule applies in tests. After the first fixture.detectChanges(), an OnPush component is clean. Assigning to fixture.componentInstance.user and calling detectChanges() again does not refresh its template, so the assertion sees old text. Setting inputs through fixture.componentRef.setInput('user', ...) marks the component dirty and avoids the problem. Later chapters cover testing in more detail.
Exercise
A parent holds filters = { status: 'open' } and passes it to an OnPush child with [filters]="filters". A button handler runs this.filters.status = 'closed'. The child still shows "open". Give the cause and two ways to fix it.
Show answer
The handler mutates the object, so the input reference is unchanged and Angular does not mark the child dirty. Fix it by replacing the object: this.filters = { ...this.filters, status: 'closed' };. Alternatively, store the filters in a signal and update them with this.filters.update(f => ({ ...f, status: 'closed' })), passing filters() to the child. The new reference then reaches the input.
Exercise
An OnPush component has message = '' and a manual socket.subscribe(m => { this.message = m; }). The template shows {{ message }}. Messages arrive, but the text only refreshes when the user clicks a button inside the component. Explain why and name two corrections.
Show answer
The subscription callback changes a plain field without notifying Angular, so the component is not marked dirty. A click inside the component dirties it, which refreshes the view and exposes the latest value. Corrections: call this.cdr.markForCheck() right after assigning, or hold the message in a signal and read message() in the template. Binding the stream with the async pipe is also valid.