Sub topic 8
Signals and OnPush
This chapter assumes you know the OnPush triggers (new input reference, event inside the component, async pipe, markForCheck) and have used @Input. It explains how signals add one more trigger, and where they still need immutable updates.
Why signals fit OnPush
With markForCheck, you must remember to tell Angular that state changed. A signal removes that step. When a template reads a signal, such as {{ count() }}, Angular records that this component's view depends on it. When the signal's value changes, Angular marks that view, and the ancestors on the path to it, for refresh at the next change detection pass.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-signal-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Count: {{ count() }}</p>
<button (click)="increment()">Add</button>
`,
})
export class SignalCounterComponent {
count = signal(0);
increment() {
this.count.update((c) => c + 1);
}
}The click would refresh this component anyway, because events inside an OnPush component mark it. The real gain appears when the write happens elsewhere, for example in a timer callback, a subscription, or a shared service. The template read is enough to get the view refreshed, with no ChangeDetectorRef.
Signals read in templates versus plain fields
Only signal reads in the template create this dependency. A plain field changed from a callback is still invisible to OnPush.
| State kind | Changed outside an event | View updates under OnPush? |
|---|---|---|
| Plain field (`count = 0`) | `this.count++` in a timer | No, unless you call `markForCheck` |
| Signal read in template | `this.count.update(...)` in a timer | Yes |
| Observable with `async` pipe | Emits a value | Yes |
Derived state with computed
computed builds values from other signals. It recalculates lazily and only when a dependency has changed, so it suits template-facing values.
Signal inputs work the same way. Use input() instead of @Input, and read the input as a function. When the parent binds a new reference, the input signal changes, and every computed and template read that depends on it updates.
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
@Component({
selector: 'app-price-tag',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ label() }}</p>`,
})
export class PriceTagComponent {
price = input.required<number>();
taxRate = input(0.2);
label = computed(
() => `${(this.price() * (1 + this.taxRate())).toFixed(2)} total`
);
}Signal inputs still follow the reference rule. A parent that mutates an object and rebinds the same reference does not change the input.
Shared state in a service
A signal held in a service lets any OnPush component read the same state. Expose it read-only so only the service can write.
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]);
}
}Every component whose template reads items() or count() refreshes when add runs, wherever it is called from.
The mutation pitfall remains
A signal decides whether it changed by comparing the old and new values with Object.is. If you change an array or object in place, the reference is the same, so the signal reports no change and nothing is marked.
// Wrong: same array reference, so dependents are not notified.
this._items().push('book');
// Right: a new array, so the signal changes.
this._items.update((list) => [...list, 'book']);Immutable updates are still the rule. A signal replaces the manual notification, not the need for new references.
Signals and zones
Under Zone.js, a timer or HTTP callback triggers a change detection pass, and a signal write marks the view so that pass refreshes it. In zoneless Angular there is no Zone.js to start passes, so a signal write is one of the notifications that schedules one. This is why OnPush components that use signals move to zoneless without code changes, while components that depend on mutated fields and the default strategy often do not. A later chapter covers zoneless in detail.
Exercise
A component uses OnPush and has total = 0 as a plain field. A setTimeout callback runs this.total = 5, and the template shows {{ total }}. The view stays at 0. Give two ways to fix it, and name one thing that would still fail if you chose the signal approach and wrote this.items().push(x) on a signal of an array.
Show answer
Fix one: call this.cdr.markForCheck() after assigning total. Fix two: make total a signal (total = signal(0)), read it as {{ total() }}, and write with this.total.set(5). The push on a signal's array still fails, because it mutates the existing array and the reference does not change, so the signal reports no change. Use this.items.update((l) => [...l, x]) instead.