Sub topic 8
Signals and OnPush
This chapter assumes you can build components with templates and bindings, and that you have read the earlier chapters on the OnPush triggers, the async pipe, and ChangeDetectorRef. You should know what markForCheck() does and why input mutation leaves an OnPush child stale. Examples target Angular 17 or later, with standalone components.
Why signals fit OnPush
OnPush answers one question: when does Angular need to look at this component again? The earlier triggers answer it indirectly. An input reference changed, an event fired in the component, or you called markForCheck(), which the async pipe does for you.
A signal answers the question directly. A signal is a wrapper around a value that tracks who reads it. When a template reads count(), Angular records that this component's view depends on that signal. When the signal's value changes, Angular knows which view is affected, so you don't need to call markForCheck().
How a template becomes a signal consumer
While Angular renders a component's template, it runs the template function inside a reactive context. Any signal you read during that run is registered as a dependency of the view. This covers these cases:
- A direct read, such as
{{ count() }}. - A read inside a
computed()that the template calls. - A read inside a method that the template calls, because the method runs during rendering.
When a registered signal changes, Angular marks the view as needing a refresh. It also marks the ancestors of that view so the next change detection pass can walk down to it. Ancestors that are OnPush and not otherwise dirty are not re-rendered. Angular only passes through them.
The next sections cover the bindings that decide what refreshes. First, the figure shows the sequence.
A signal in a component
The simplest case is local state, as in the counter below.
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-signal-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Count: {{ count() }} (double: {{ double() }})</p>
<button (click)="increment()">Add</button>
`,
})
export class SignalCounterComponent {
count = signal(0);
double = computed(() => this.count() * 2);
increment() {
this.count.update((c) => c + 1);
}
}The click handler already marks an OnPush component for checking, so this example would work with a plain field too. The difference appears when the change does not come from an event in the component. Consider a service that holds shared state.
import { Injectable, computed, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartStore {
private readonly _items = signal<string[]>([]);
readonly items = this._items.asReadonly();
readonly count = computed(() => this._items().length);
add(item: string) {
this._items.update((list) => [...list, item]);
}
}import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { CartStore } from './cart.store';
@Component({
selector: 'app-cart-badge',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<span>Cart: {{ store.count() }}</span>`,
})
export class CartBadgeComponent {
protected store = inject(CartStore);
}Suppose a button three levels away in the tree calls store.add('book'). CartBadgeComponent has no input change and no event of its own. With a plain field it would stay stale until something else marked it. Here the template read store.count(), so the write to _items invalidates count, which marks the badge's view. The badge updates.
asReadonly() exposes the signal without a set method, so only the store can write to it. That keeps the data flow easy to follow.
Signals versus the earlier mechanisms
| Mechanism | What tells Angular to check | You must remember to |
|---|---|---|
| Plain field mutated in a callback | Nothing, unless an event in the component or another trigger happens to fire | Call `markForCheck()` yourself |
| Observable with `async` pipe | The pipe calls `markForCheck()` on each emission | Use the pipe in the template |
| Manual subscription | Your call to `markForCheck()` | Call it and unsubscribe |
| Signal read in the template | The signal's change notification | Read it in the template (or in a method or `computed` the template uses) |
Signals remove the "remember" column for most cases. They also make dependencies precise. A computed() re-runs only when its own dependencies change, and its result is cached.
Signal inputs
Angular 17.1 added signal-based inputs. The input() function replaces the @Input decorator and gives you a read-only signal.
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
export interface User {
name: string;
}
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ displayName() }}</p>`,
})
export class UserCardComponent {
user = input.required<User>();
displayName = computed(() => this.user().name.toUpperCase());
}When the parent binds a new object reference, the user signal gets a new value. displayName is invalidated, and the view refreshes. Using computed() for derived values replaces the ngOnChanges and setter patterns that decorator inputs needed.
Signal inputs do not change the reference rule. The input signal compares values with Object.is, so the same object reference counts as no change. In the parent below, renameByMutation() still leaves the card stale.
import { Component } from '@angular/core';
import { User, UserCardComponent } from './user-card.component';
@Component({
selector: 'app-parent',
imports: [UserCardComponent],
template: `
<app-user-card [user]="user" />
<button (click)="renameByMutation()">Mutate</button>
<button (click)="renameImmutably()">Replace</button>
`,
})
export class ParentComponent {
user: User = { name: 'Ada' };
renameByMutation() {
// Same reference: the input signal does not change, so the computed stays cached.
this.user.name = 'Grace';
}
renameImmutably() {
// New reference: the input signal changes and the card refreshes.
this.user = { ...this.user, name: 'Grace' };
}
}The failure is a little worse than with decorator inputs. The computed cache keeps the old uppercase name even if something else forces the view to refresh, because the computed has no reason to re-run. Treat objects passed into signal inputs as immutable.
If you need two-way binding, model() creates a signal input that the child can also write to. The parent receives the write through [(value)] syntax.
Signals hold references too
A signal does not watch the inside of its value. It notifies when the value you set is a different value, using Object.is by default. Mutating an array or object inside a signal is invisible.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-todo-list',
template: `
<ul>
@for (t of todos(); track t) {
<li>{{ t }}</li>
}
</ul>
<button (click)="addWrong()">Add (broken)</button>
<button (click)="addRight()">Add</button>
`,
})
export class TodoListComponent {
todos = signal<string[]>(['Write chapter']);
addWrong() {
// Same array reference: the signal does not notify, so the list does not update.
this.todos().push('Review');
}
addRight() {
// New array: the signal notifies and the view refreshes.
this.todos.update((list) => [...list, 'Review']);
}
}The array in addWrong is mutated anyway, so the next real update will show the pushed item. That makes the bug look intermittent. You can pass { equal: myFn } to signal() or computed() to define your own equality, but a custom equal that returns true for different data hides real changes. Use it only when you can prove the two values are interchangeable.
Bridging Observables with toSignal
toSignal() from @angular/core/rxjs-interop subscribes to an Observable and exposes the latest value as a signal. It unsubscribes when the injection context is destroyed. The example below replaces the async pipe sample from earlier.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { timer } from 'rxjs';
@Component({
selector: 'app-clock-ticks',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds elapsed: {{ seconds() }}</p>`,
})
export class ClockTicksComponent {
seconds = toSignal(timer(0, 1000), { initialValue: 0 });
}Points to know:
- Call
toSignalin an injection context, such as a field initializer or the constructor. - A signal must always have a value. Without
initialValue, the type isT | undefined. UseinitialValuewhen you have a sensible default. - If the Observable errors, reading the signal throws that error. Handle errors in the pipe with
catchError. - It subscribes immediately, once. It does not give you the lazy behavior of
asyncin a conditionally rendered template block.
The opposite direction, toObservable(), emits when a signal changes, but it delivers values asynchronously through an effect.
Where signals do not help
Reading a signal outside a reactive context creates no dependency. These cases are not tracked:
- Reading in
ngOnInit, a constructor, or an event handler. The read returns the current value and nothing more. - Copying a signal's value into a plain field, such as
this.label = this.name(). The field is a snapshot, and it will not update when the signal changes. - Reading inside a
setTimeoutor a subscription callback.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-snapshot-bug',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Snapshot: {{ snapshot }}</p>
<p>Live: {{ name() }}</p>
<button (click)="name.set('Grace')">Rename</button>
`,
})
export class SnapshotBugComponent {
name = signal('Ada');
snapshot = this.name(); // read once at construction, never updated
}After the click, "Live" shows Grace and "Snapshot" still shows Ada. If you need a derived value, use computed(() => this.name()).
Does a signal change still need a change detection run?
A signal marks the view, but Angular still has to run a change detection pass to update the DOM. In an application that uses Zone.js, a pass normally follows async work that runs inside the Angular zone. Since Angular 18, the framework also schedules a pass itself when a signal read by a template changes, so a write from code that runs outside the zone is still rendered. On earlier versions, such a write could wait for the next zone-triggered pass.
This is the link to the zoneless chapter. When Zone.js is removed, signals, markForCheck(), the async pipe, and event listeners are the notification sources. Components that already use OnPush with signals need little or no change.
Testing signal-based OnPush components
Set signal inputs with componentRef.setInput(), as for decorator inputs. Writes to a signal from a store mark the view without any extra call.
import { TestBed } from '@angular/core/testing';
import { CartBadgeComponent } from './cart-badge.component';
import { CartStore } from './cart.store';
describe('CartBadgeComponent', () => {
it('updates when the store changes', () => {
const fixture = TestBed.createComponent(CartBadgeComponent);
const store = TestBed.inject(CartStore);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Cart: 0');
store.add('book');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Cart: 1');
});
});The second detectChanges() renders because the store write marked the badge's view. The same test with a plain field in the store would still show Cart: 0 for an OnPush component.
Summary of rules
- Read signals in the template, or in a
computed()that the template calls. - Update signals with
setorupdateusing new references. Never mutate the value inside. - Use
computed()for derived state instead of copying values into fields. - Use
toSignal()or the async pipe for Observables. - Expect an input signal to ignore mutation of an object that the parent keeps the same.
Exercise
A component has items = signal<string[]>([]) and an OnPush template that loops over items(). A method calls this.items().push('x'). The list does not update. Why, and how do you fix it?
Show answer
push mutates the array in place, so the signal's value is still the same reference. The signal compares with Object.is, sees no change, and never notifies the view. Replace the array instead: this.items.update((list) => [...list, 'x']).
Exercise
What is the difference between name = signal('Ada'); label = this.name(); and label = computed(() => this.name()); in an OnPush component whose template shows label or label()?
Show answer
The first line reads the signal once, during construction, and stores a plain string. It never updates. The second creates a derived signal that tracks name. When name changes, the template's read of label() is invalidated and the view refreshes.
Exercise
A parent keeps one User object and calls this.user.name = 'Grace'. The child has user = input.required<User>() and a computed that uppercases user().name. The child still shows "ADA". Name two valid fixes.
Show answer
Either replace the object in the parent with a new reference (this.user = { ...this.user, name: 'Grace' }), or make the user a signal of an immutable value and update it with set/update using a copy. Both give the child's input signal a different value, which invalidates the computed.