Sub topic 5
Signals as the primary source of updates
This chapter assumes you can build standalone components, know the basics of signal() and computed(), and understand that the default change detection model checks the component tree after Zone.js reports async work. Here you will see how a signal read in a template tells Angular when to update the view, and why that matters once Zone.js is gone.
Why signals fit zoneless mode
In a zone-based app, Angular does not know which piece of state changed. Zone.js patches browser APIs such as setTimeout, addEventListener and Promise. When one of those finishes, Angular runs change detection over the tree and compares template bindings with their previous values.
Without Zone.js, nothing reports that async work finished. Angular needs another source of "something changed." Signals provide it. A signal is a value container that tracks who reads it. When the value changes, it notifies those readers directly.
A template is one such reader. When a component template reads count(), Angular records that the template depends on the count signal. When count is set, Angular marks that component's view for refresh and schedules change detection.
How a template subscribes to a signal
Angular runs each template inside a reactive context. Any signal read during rendering is registered as a dependency of that view. This happens automatically, so you do not subscribe or unsubscribe.
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-cart',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Items: {{ items().length }}</p>
<p>Total: {{ total() }}</p>
<button (click)="add(10)">Add item</button>
`,
})
export class Cart {
protected readonly items = signal<number[]>([]);
protected readonly total = computed(() => this.items().reduce((a, b) => a + b, 0));
add(price: number) {
this.items.update((list) => [...list, price]);
}
}The template reads items() and total(). The total signal is a computed signal, so it reads items internally and recalculates only when items changes. Calling add() replaces the array with a new one, so the signal sees a new value and notifies its readers.
The notification path
The sequence below shows what happens from a signal write to a screen update.
Two details matter here. First, the scheduler batches work: several signal writes in the same task lead to one change detection run. Second, only the views marked for refresh, and their ancestors on the path to the root, are checked.
What counts as a change
A signal notifies its readers only when the new value differs from the old one. By default, Angular compares with Object.is. This has direct consequences for objects and arrays.
import { signal } from '@angular/core';
const user = signal({ name: 'Ada', visits: 1 });
// Mutating the object in place: the signal still holds the same reference.
user().visits++; // No notification. The template will not update.
// Replacing the value: a new reference, so readers are notified.
user.update((u) => ({ ...u, visits: u.visits + 1 }));In a zone-based app, the in-place mutation might appear to work, because Zone.js triggers a check after the event and the default strategy re-evaluates every binding. In a zoneless app, it silently fails. Treat signal values as immutable and replace them.
You can also pass a custom equal function to signal() or computed() when you want a different definition of "same."
Common signal-based patterns
Derived state with computed
Use computed() for values derived from other signals. The result is cached and recalculated lazily, so it is cheap to read in a template many times.
Input signals
Signal inputs created with input() are signals too. When a parent changes the bound value, the child's input signal changes, and the child view updates. This works without Zone.js.
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
@Component({
selector: 'app-price',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<span>{{ formatted() }}</span>`,
})
export class Price {
readonly amount = input.required<number>();
protected readonly formatted = computed(() => `$${this.amount().toFixed(2)}`);
}Side effects with effect
Use effect() to run code when signals change, for example to write to localStorage or a logger. Do not use effects to copy one signal into another. Use computed() or linkedSignal() for that. Effects that set signals are harder to follow and can cause extra change detection runs.
Bridging RxJS
Observables do not notify Angular on their own. Two tools convert them into signals:
toSignal(observable$)subscribes and exposes the latest value as a signal. PassinitialValueif the stream does not emit synchronously, or the signal type includesundefined.- The
asyncpipe in a template also marks the view for check when a new value arrives. Chapter 8 covers it in detail.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Ticks: {{ ticks() }}</p>`,
})
export class Ticker {
protected readonly ticks = toSignal(interval(1000), { initialValue: 0 });
}The subscription is cleaned up when the component is destroyed, because toSignal is tied to the injection context where it was called.
Where signals are not enough
Signals only help when the changing state is a signal and the template reads it. These cases still miss updates:
| Situation | Why it fails | Fix |
|---|---|---|
| Plain field changed in a `setTimeout` | Nothing notifies Angular | Make it a signal |
| Object mutated in place inside a signal | Same reference, no notification | Replace the value |
| Signal read only inside `untracked()` or an event handler | No dependency is recorded | Read it during rendering |
| Third-party code changing DOM or state | Angular is not told | Wrap the state in a signal or call `markForCheck()` |
A signal read in an event handler does not make the template depend on it. Only reads during template evaluation, inside computed() or inside effect() create dependencies.
Conditional reads and dependency tracking
Dependencies are tracked per run, not declared in advance. In a computed(), only signals actually read are dependencies.
import { computed, signal } from '@angular/core';
const showDetails = signal(false);
const details = signal('Long description');
const label = computed(() => (showDetails() ? details() : 'Hidden'));While showDetails is false, label depends only on showDetails. Changes to details do not recompute it. Once showDetails becomes true, the next evaluation reads details, and it becomes a dependency. This is correct behavior, but it means you should read every signal you need before any early return that skips it, if you want it tracked.
Practical checklist
- Put state that appears in templates in signals.
- Update signals with
set()orupdate(), and create new objects and arrays instead of mutating. - Use
computed()for derived values. - Convert observables with
toSignal()or use theasyncpipe. - Use
OnPushon components so the zone-based and zoneless behavior match during migration.
Exercise
A component holds items = signal<string[]>([]) and an addItem(name) method that runs this.items().push(name). The app is zoneless. The template shows items().length. Why does the count never change, and what is the smallest fix?
Show answer
push mutates the existing array, so the signal still holds the same reference. Object.is reports no change, so no readers are notified and no change detection is scheduled. Replace the value instead: this.items.update((list) => [...list, name]);.
Exercise
Given const label = computed(() => (showDetails() ? details() : 'Hidden')); and showDetails is false, does setting details to a new string recompute label? Explain.
Show answer
No. Dependencies are tracked on each evaluation, and while showDetails() is false, details is never read, so it is not a dependency. When showDetails becomes true, the next evaluation reads details and starts tracking it.