Sub topic 10
Signals in templates and OnPush components
This chapter assumes you know the Default and OnPush strategies, input reference checks, and markForCheck from the earlier chapters. It also assumes you can read basic signal syntax: signal(), .set(), .update(), and reading with count().
What a signal changes about OnPush
An OnPush component is normally checked in four cases:
- An input reference changes.
- An event fires in its template.
- Something calls
markForCheck. - The
asyncpipe receives a value.
Signals add a fifth case. When a template reads a signal, Angular records that the component's view depends on it. When the signal changes, Angular marks that view for refresh. No input change, template event, or manual call is needed.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<button (click)="increment()">Clicked {{ count() }} times</button>`,
})
export class Counter {
count = signal(0);
increment() {
this.count.update((c) => c + 1);
}
}The click would already refresh this component, because template events always do. The real benefit shows when the signal changes somewhere else, such as a timer, a service, or a response callback. That is the case where a plain field would leave an OnPush view stale.
How Angular tracks the dependency
Each component view has a reactive consumer. While Angular runs the template function, it records every signal read during that run. The reads are what create the dependency. Nothing is declared ahead of time.
When one of those signals changes, the consumer is notified. Angular then does three things:
- It flags the component's view as needing a refresh.
- It flags each ancestor view as having a child to visit.
- It schedules a change detection run if none is pending.
On the next run, Angular walks from the root as usual. It passes through the flagged ancestors without re-evaluating their own bindings. It refreshes only the view that read the signal.
This differs from markForCheck. That method marks the component and every ancestor as dirty, so each ancestor's own bindings are re-evaluated too. A signal-driven update refreshes less.
Derived values with computed
A computed signal is a read-only signal derived from other signals. It is lazy and memoized: it recalculates only when a dependency has changed and someone reads it. Signal inputs, created with input(), are signals too, so a computed can depend on them.
import { CurrencyPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
interface Item {
price: number;
}
@Component({
selector: 'app-cart-total',
imports: [CurrencyPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ count() }} items, total {{ total() | currency }}</p>`,
})
export class CartTotal {
items = input.required<Item[]>();
count = computed(() => this.items().length);
total = computed(() => this.items().reduce((sum, i) => sum + i.price, 0));
}The template reads count() and total(). Both depend on items(). When the parent passes a new array, the input signal changes, the computed values are marked stale, and the view refreshes. If the parent passes the same array reference, nothing happens, as with any OnPush input.
Put derived logic in computed rather than in a template method. A method like getTotal() runs on every check of the view. A computed value runs only when its inputs change.
Change detection still runs, but narrower
A signal does not update the DOM by itself. It tells Angular which view needs work, and Angular still performs a change detection run. The signal narrows what that run does.
In a Zone.js app, an event such as a click triggers a run from the root. Components using Default still get checked on that run. Signals do not remove that cost. To get the full benefit, make components OnPush and keep their changing state in signals.
Recent Angular versions also schedule a run when a signal read by a template changes, even when Zone.js saw no event. Older versions did not. If you support an older version, check its documentation before relying on this.
Where tracking does not happen
Only reads performed while the template runs, or inside a computed or effect, are tracked. Common mistakes:
- Reading in a lifecycle hook or event handler.
ngOnInit() { this.label = this.name(); }copies the current value once. The copy never updates, and the template shows stale text. - Mutating the value inside a signal. A signal notifies only when the new value differs from the old one. The default comparison is
Object.is, so the same object or array reference counts as unchanged. - Plain fields next to signals. A plain field changed in a timer is still invisible to an OnPush view. The view refreshes only if it also reads a changed signal.
The second mistake is the most frequent. Compare these two methods:
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-todos',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (todo of todos(); track todo) {
<li>{{ todo }}</li>
}
</ul>
<button (click)="addWrong()">Add (mutate)</button>
<button (click)="add()">Add (replace)</button>
`,
})
export class Todos {
todos = signal<string[]>(['Write chapter']);
addWrong() {
this.todos().push('Mutated'); // same array reference: no notification
}
add() {
this.todos.update((list) => [...list, 'Replaced']); // new array: view refreshes
}
}The click on addWrong is an event in the template, so the view is checked anyway, and the pushed item may appear by accident. If the same mutation happened in a timer, the view would stay stale. This coincidence makes the bug hard to spot in testing. Treat signal values as immutable, just as you treat OnPush inputs.
Sharing state through a service
A signal held in a service lets unrelated OnPush components stay in sync without an input chain or markForCheck.
import { ChangeDetectionStrategy, Component, Injectable, inject, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeStore {
readonly theme = signal<'light' | 'dark'>('light');
toggle() {
this.theme.update((t) => (t === 'light' ? 'dark' : 'light'));
}
}
@Component({
selector: 'app-theme-label',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<span>Theme: {{ store.theme() }}</span>`,
})
export class ThemeLabel {
protected store = inject(ThemeStore);
}
@Component({
selector: 'app-theme-button',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<button (click)="store.toggle()">Toggle theme</button>`,
})
export class ThemeButton {
protected store = inject(ThemeStore);
}ThemeLabel has no inputs and no event handlers, yet it updates when ThemeButton toggles the theme. Only ThemeLabel needs a refresh, so Angular flags only its view and the path to it.
Choosing between the tools
| Situation | Preferred tool |
|---|---|
| State owned by the component and read in its template | `signal` |
| Value derived from other state | `computed` |
| Data arriving from an Observable | `async` pipe, or `toSignal` |
| Legacy field changed outside Angular's knowledge | `markForCheck` |
| Parent hands data to a child | Signal input, passed as a new reference |
toSignal converts an Observable into a signal. This lets a template read stream data the same way as other state, and it unsubscribes when the component is destroyed.
Common errors
- Calling a signal in the template without parentheses.
{{ count }}prints the function, not the number. Write{{ count() }}. - Writing to a signal inside a
computed. Computed functions must be pure. Writing there throws an error. - Expecting
effectto update the view. Aneffectruns side effects after the state changes. Put values the template needs in a signal orcomputed, and read them in the template. - Reading a signal behind a condition. Dependencies are collected on each run. If a read sits in a branch that is not taken, that signal is not a dependency for that run. This is correct behavior, but it can surprise you while debugging.
Exercise
A component is OnPush. Its template shows {{ status }}, a plain string field. A setTimeout callback sets this.status = 'ready' after two seconds, and the page never changes. Give two ways to fix it, and say which one lets Angular refresh only this component's view without re-evaluating its ancestors' own bindings.
Show answer
Option one: inject ChangeDetectorRef and call markForCheck() after setting the field. This marks the component and all its ancestors dirty, so ancestors' bindings are re-evaluated too. Option two: make status a signal, status = signal('loading'), read it as {{ status() }}, and call this.status.set('ready') in the timer. The template read creates the dependency, so Angular flags only this view for refresh and the ancestors for traversal. The signal option refreshes only this component's view.
Exercise
A signal holds an array: items = signal<string[]>([]). A button handler calls this.items().push('x'), and an OnPush template that reads items() in a @for loop does not show the new item when the push happens inside a timer. Explain why and write the corrected line.
Show answer
The array reference is unchanged, and a signal compares values with Object.is by default, so it sends no notification and the view is not flagged. Replace the array instead: this.items.update((list) => [...list, 'x']);. The new reference makes the signal notify its consumers, so the view refreshes.