Sub topic 5
How Templates React to Signals: OnPush and Zoneless
The earlier chapters treated signals as values you read and write. This chapter covers the other end: how Angular notices that a template needs to change, and how signals let you drop Zone.js and the broad, tree-wide checks it drives.
This chapter assumes you know how to build components with templates and bindings, have a rough idea of what change detection is, and have read the earlier chapters on signal() and computed(). The examples target Angular 20 or later, where zoneless change detection is stable. Notes point out where older versions differ.
What change detection does
Change detection is the process Angular uses to keep the DOM in sync with component state. During a pass, Angular walks the component tree. For each component it checks, it runs that component's template bindings, compares each result with the previous one, and updates the DOM where the two differ.
That leaves two questions:
- When does a pass start?
- Which components does a pass check?
Classic Angular answers both broadly. Zone.js patches browser APIs such as setTimeout, addEventListener, Promise.then, and XHR. When any of those callbacks finishes, Angular starts a pass. With the default strategy, that pass checks every component. Angular cannot tell what changed, so it checks everything.
Signals give Angular precise answers to both questions.
The template is a reactive consumer
When Angular renders a component's template, it runs the template inside a reactive context. That is the same dependency-tracking mechanism computed() uses. Every signal the template reads during rendering becomes a dependency of that component's view.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-clock',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Signal time: {{ now() }}</p>
<p>Plain field time: {{ plainNow }}</p>
`,
})
export class ClockComponent {
now = signal(new Date().toLocaleTimeString());
plainNow = new Date().toLocaleTimeString();
constructor() {
setInterval(() => {
const t = new Date().toLocaleTimeString();
this.now.set(t); // notifies the template; this view is marked for refresh
this.plainNow = t; // Angular is not told about this change
}, 1000);
}
}The first paragraph updates every second. Calling set() notifies every consumer of now, and one of those consumers is the template. Angular marks this view for refresh and schedules a pass.
The second paragraph is different. In an OnPush component running under Zone.js, the setInterval callback does start a pass. That pass skips this component, though, because nothing marked it dirty. You will often see the plain field update only because the signal update next to it marked the view dirty in the same tick. Delete the now.set(t) line and the plain field stays frozen.
A read inside a getter or a method that the template calls still counts. Tracking follows the call stack, so {{ fullName() }} and {{ summary }}, where summary is a getter that calls this.first(), both register their dependencies. Signals are tracked no matter where you write the read, as long as it happens during the template's execution.
How a signal change reaches the DOM
The detail that matters is step E. Before Angular 17, the only API for this job was markForCheck(), and it marks the component and every ancestor dirty, so each of them re-runs its bindings. A signal notification marks only the consumer view for refresh. Its ancestors get a lighter flag that means "a descendant needs work." Angular passes through those ancestors without re-checking their own bindings, as long as they are OnPush and otherwise clean.
People sometimes call this local or targeted change detection. In a large OnPush tree, a signal change deep in the tree refreshes one component instead of a whole branch.
Signals and OnPush
OnPush tells Angular to skip a component unless something gives it a reason to check. Under OnPush, any of these marks a component dirty:
- An
@Input()orinput()receives a new value, compared by reference. - An event bound in its template fires, or an event bubbles up from a child's template.
- Code calls
ChangeDetectorRef.markForCheck(). - The
asyncpipe receives a new value, because it callsmarkForCheck()internally. - A signal read in its template changes.
The last item makes OnPush easy to use. Before signals, OnPush components forced you to use immutable inputs, the async pipe, or manual markForCheck() calls. With signals, you hold state in a signal, read it in the template, and the component updates whenever the state changes, from whatever source.
The mutation trap
Signals use Object.is as their default equality check. If you mutate an object or array in place and then call set() with the same reference, the signal sees no change and notifies no one. The template does not refresh.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-todo-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button (click)="addBroken()">Add (broken)</button>
<button (click)="addCorrect()">Add (correct)</button>
<p>{{ todos().length }} items</p>
`,
})
export class TodoListComponent {
todos = signal<string[]>([]);
addBroken() {
this.todos().push('new'); // mutates in place
this.todos.set(this.todos()); // same reference, so no notification
}
addCorrect() {
this.todos.update(list => [...list, 'new']); // new array, so consumers notified
}
}In this example, addBroken can still appear to work. The button click is a template event, and template events mark the component dirty on their own, so the count re-renders. If you move the same code into a setTimeout or a service callback, the bug shows up. A bug that only appears depending on what triggered the change is hard to track down, so replace arrays and objects instead of mutating them.
Zoneless change detection
Once your templates depend on signals, Zone.js has much less to do. Zoneless mode removes it. Angular then starts a pass only when something explicitly tells it to.
Enabling it
import { bootstrapApplication } from '@angular/platform-browser';
import { provideZonelessChangeDetection } from '@angular/core';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [provideZonelessChangeDetection()],
}).catch(err => console.error(err));Then remove zone.js from the polyfills arrays in angular.json, for both the build and test targets. Also delete any import 'zone.js' lines. In Angular 18 and 19 the provider was called provideExperimentalZonelessChangeDetection(). Angular 20 stabilized it under the name shown above, and Angular 21 makes zoneless the default for new projects.
Removing Zone.js shrinks the bundle and removes the patching overhead on every async callback. Stack traces also get shorter. Change detection then happens only when your code gives Angular a reason.
What schedules a pass without Zone.js
| Trigger | Zone.js, default strategy | Zone.js, OnPush | Zoneless |
|---|---|---|---|
| Signal read in template changes | Pass, view refreshed | Pass, view refreshed | Pass, view refreshed |
| Template event listener fires | Pass, all checked | Pass, component marked | Pass, component marked |
| `markForCheck()` / `async` pipe | Pass | Pass, component marked | Pass, component marked |
| `ComponentRef.setInput()` | Pass | Pass, component marked | Pass, component marked |
| Plain field changed in `setTimeout` | Pass, field rendered | Pass, component skipped | No pass at all |
| Plain field changed after `fetch().then()` | Pass, field rendered | Pass, component skipped | No pass at all |
The last two rows cause most migration bugs. Code that "just worked" under the default strategy because Zone.js caught every callback stops updating the screen. The fix is nearly always to move that state into a signal.
Code that waits for zone stability
Some code relies on NgZone.onStable, NgZone.onMicrotaskEmpty, or zone.run() to know when rendering has finished. In zoneless mode, those NgZone events never fire. Replace them with afterNextRender() or afterEveryRender() (called afterRender() before Angular 20). These hooks run after Angular has written to the DOM, whatever triggered the pass. Testing code changes as well: rather than relying on fixture.detectChanges() after every change, call await fixture.whenStable() and let the scheduler run as it would in the app.
Third-party libraries that mutate component state from their own callbacks have the same problem. Wrap their callbacks so they write to a signal, or call markForCheck().
Effects and the rendering cycle
Effects connect to change detection too. In Angular 19 and later, an effect created inside a component runs during change detection, just before Angular checks that component's view. Signals the effect writes are already updated when the template reads them. Effects created outside components, called root effects, such as those in services, run before the component tree is checked.
Even so, if one value can be computed from another, use computed() rather than an effect that writes a second signal. A computed value is pulled lazily during the template read and never causes an extra pass. An effect that writes a signal read earlier in the same pass makes Angular re-check, and in dev mode a loop that never settles throws an error.
Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| Template never updates after async work | Plain field under OnPush or zoneless | Store the value in a signal |
| Updates only when you click something | In-place mutation hidden by an event-triggered check | Replace the array or object in `update()` |
| Value is stale after first render | Signal copied into a field in `ngOnInit` | Read the signal in the template or use `computed()` |
| DOM measurement code runs too early | Relied on `NgZone.onStable` | Use `afterNextRender()` |
| `ExpressionChangedAfterItHasBeenChecked` | Writing signals during template rendering | Move writes to event handlers, or use `computed()` |
Exercise
An OnPush component has a plain field status = 'idle' shown as {{ status }}. A service callback, fired from a WebSocket message, sets component.status = 'connected'. The app uses Zone.js. Does the text update? What changes if you switch the app to zoneless, and what is the cleanest fix that works in both setups?
Show answer
Under Zone.js the WebSocket callback starts a pass, but the OnPush component is not marked dirty, so Angular skips it and the text stays 'idle'. Under zoneless no pass is even scheduled. The cleanest fix is to make status a signal, status = signal('idle'), read it as {{ status() }}, and update it with status.set('connected'). The signal write marks the view for refresh and schedules a pass in both setups.
Exercise
A parent and a child component both use OnPush. Only the child's template reads count(). When count changes, which components re-run their template bindings, and how does that differ from calling markForCheck() in the child?
Show answer
Only the child refreshes. The signal notification marks the child's view for refresh and gives the parent a lighter flag that only tells Angular to pass through it to reach the child. markForCheck() marks the child and every ancestor dirty, so the parent re-runs its bindings too.
Exercise
You enable provideZonelessChangeDetection() and a chart library that used this.ngZone.onStable.subscribe(() => this.chart.resize()) stops resizing. Why, and what should replace it?
Show answer
Without Zone.js, NgZone is a no-op and onStable never emits. Replace the subscription with afterEveryRender(() => this.chart.resize()) (or afterNextRender for one-time work), registered in an injection context such as the constructor. These hooks run after every change detection pass, whatever triggered it.