Sub topic 1
Recap: writable signals
This chapter reviews writable signals, the base that computed() and effect() build on. The details here (equality checks, immutable updates, read-only views) explain much of how derived state behaves in the later chapters.
Prerequisites
This chapter assumes you already have:
- Basic TypeScript: generics, interfaces, arrow functions and spread syntax.
- Angular components, templates and dependency injection at a working level. You should know what
@Component,@Injectableandinject()do. - A high-level picture of change detection: Angular decides when to re-render a component's template.
You do not need to know RxJS. It appears only in the last chapter.
What a writable signal is
A signal is a wrapper around a value that tells Angular when the value changes. A writable signal is a signal you can change directly. You create one with signal() and give it an initial value.
import { signal } from '@angular/core';
const count = signal(0);
console.log(count()); // 0The signal is a function. Calling it with no arguments reads the current value. The call matters because it is how Angular learns who depends on the signal. A template or a computed value that calls count() registers itself as a consumer. When count changes, Angular notifies those consumers.
The type of count is WritableSignal<number>. TypeScript infers it from the initial value. When the initial value is narrower than you want, give the type explicitly.
import { signal } from '@angular/core';
type Status = 'idle' | 'loading' | 'error';
const status = signal<Status>('idle');
const selectedId = signal<number | null>(null);
console.log(status(), selectedId()); // idle nullWithout the generic argument, signal(null) would be inferred as WritableSignal<null>, and you could never store a number in it.
Changing a value: set and update
A writable signal has two main ways to change its value.
set(value)replaces the value with the one you give.update(fn)computes the new value from the current one. The function receives the current value and returns the new value.
import { signal } from '@angular/core';
const count = signal(0);
count.set(5);
console.log(count()); // 5
count.update((c) => c + 1);
console.log(count()); // 6Use update() whenever the new value depends on the old one. It avoids reading the signal separately and writing back. For a plain replacement, set() is clearer.
Both methods are synchronous. After set() returns, the next read already sees the new value. Consumers such as templates are notified, but they re-run later, not inside the set() call.
Signals in a component
Signals are usually stored as fields on a component or service. A template reads a signal by calling it, like any other function.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<p>Count: {{ count() }}</p>
<button (click)="increment()">+1</button>
<button (click)="reset()">Reset</button>
`,
})
export class CounterComponent {
count = signal(0);
increment() {
this.count.update((c) => c + 1);
}
reset() {
this.count.set(0);
}
}When the template calls count(), Angular records that this component's view depends on count. After increment() runs, Angular knows this view needs a refresh. This precise knowledge is what lets signals support finer-grained updates than checking every binding.
A common mistake is writing {{ count }} in the template. This renders the function itself instead of its value, and in strict template checking it can produce a type error in some positions. Always call the signal.
What happens when you write
Writing to a signal does not always notify consumers. Before notifying, the signal compares the new value with the current one. If they are considered equal, nothing happens.
The default equality check is Object.is, which behaves like === with two differences that rarely matter (NaN equals NaN, and +0 differs from -0). For primitives, this does what you expect. Setting count to 5 when it is already 5 does nothing.
For objects and arrays, Object.is compares references, not contents. This leads to the most common signal mistake, covered next.
Objects and arrays: update immutably
Suppose a signal holds an object. If you change a property in place, the reference stays the same, so the signal sees no change.
import { signal } from '@angular/core';
interface User {
name: string;
tags: string[];
}
const user = signal<User>({ name: 'Ada', tags: ['math'] });
// Wrong: same object reference, so no consumer is notified
user().tags.push('code');
// Right: build a new object and a new array
user.update((u) => ({ ...u, tags: [...u.tags, 'code'] }));
console.log(user().tags); // ['math', 'code']The first line does change the data, which is why a later read would show it. But no consumer is told. A template that already rendered user().tags keeps showing the old list until something else triggers a refresh. Computed values built on user keep returning their cached result for the same reason.
The rule is to treat the value inside a signal as immutable. Produce a new object or array whenever something changes. Spread syntax covers most cases.
| Change you want | Immutable pattern |
|---|---|
| Add to an array | `list.update((l) => [...l, item])` |
| Remove from an array | `list.update((l) => l.filter((x) => x.id !== id))` |
| Replace one item | `list.update((l) => l.map((x) => (x.id === id ? { ...x, done: true } : x)))` |
| Change one property | `obj.update((o) => ({ ...o, name: 'Grace' }))` |
Earlier previews of the signals API had a mutate() method for in-place changes. It was removed before signals were stabilized. If you find it in older articles, replace it with update() and a new value.
Custom equality on a signal
Every signal accepts an equal option, a function that decides whether two values count as the same. Use it when the default reference check is too strict or too loose for your data.
import { signal } from '@angular/core';
const name = signal('Ada', {
equal: (a, b) => a.toLowerCase() === b.toLowerCase(),
});
name.set('ADA'); // treated as equal, so the signal keeps 'Ada' and notifies nobody
console.log(name()); // 'Ada'
name.set('Grace'); // different, so the signal stores it and notifies consumers
console.log(name()); // 'Grace'When equal returns true, the signal keeps the old value, not the new one. Custom equality is mostly useful on computed values, where Angular creates new arrays and objects on every recalculation. A later chapter returns to it. For a writable signal, the default is usually right, and the immutable update pattern is the better fix for most problems.
Exposing a signal as read-only
A service often owns state that components should read but not change. asReadonly() returns a Signal<T> view of a writable signal. The view has no set() or update().
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly _count = signal(0);
readonly count = this._count.asReadonly();
add() {
this._count.update((c) => c + 1);
}
clear() {
this._count.set(0);
}
}A component that injects CartService can call cart.count() in its template, but cart.count.set(1) fails to compile. All writes go through add() and clear(), so the rules for changing the cart live in one place.
This pairing of a private writable signal with a public read-only one is the standard pattern. It also shows the two types you will see throughout this tutorial:
WritableSignal<T>can be read and written.Signal<T>can only be read. Everycomputed()returns this type, and so doesasReadonly().
A function that only needs to read a value should accept a Signal<T>. A WritableSignal<T> is assignable to it, so callers can pass either kind.
import { Signal, signal } from '@angular/core';
function describe(value: Signal<number>): string {
return `The value is ${value()}`;
}
const count = signal(3);
console.log(describe(count)); // The value is 3Reading without a component
Signals are plain objects and work outside components and templates. The earlier examples ran as ordinary TypeScript. The difference between a template and a plain function is only who is listening. A bare count() call in a function reads the value and registers nothing. A read inside a template, a computed() or an effect() registers a dependency. The next chapters build on this distinction.
Some operations have rules about where they may run. Writing to a signal from inside a computed() callback throws an error, because a derived value must not change other state while it is being calculated. Effects have their own rules for writes, covered when they are introduced.
Common mistakes
- Forgetting the parentheses.
countis the signal object.count()is the value. Inif (count > 3), TypeScript reports a type error, butif (count)compiles and is always true, because a function is truthy. - Mutating in place. Pushing into an array or assigning to a property inside a signal does not notify consumers. Write new references.
- Storing derived data in a writable signal. If a value can be calculated from other signals, keeping a second writable copy invites the two to drift apart. The next chapter shows how
computed()solves this. - Exposing the writable signal. Public writable signals on services let any component change shared state. Use
asReadonly(). - Expecting a write to run consumers immediately.
set()marks consumers dirty. Templates and effects re-run later, so code that reads a template-bound value right afterset()should not expect the DOM to be updated yet.
Quick reference
| API | Purpose |
|---|---|
| `signal(initial)` | Create a writable signal. |
| `signal(initial, { equal })` | Create one with a custom equality check. |
| `sig()` | Read the current value and register a dependency if one is listening. |
| `sig.set(value)` | Replace the value. |
| `sig.update((v) => next)` | Compute the next value from the current one. |
| `sig.asReadonly()` | Get a `Signal<T>` that cannot be written. |
Exercise
A component has items = signal<string[]>(['a', 'b']). A button handler runs this.items().push('c'), and the template shows {{ items().length }}. The list data now has three entries, but the page still shows 2. Why, and how do you fix it?
Show answer
The push() call changes the array in place, so the signal's value keeps the same reference. The signal compares the old and new values with Object.is, finds no change, and never notifies the template. Write a new array instead: this.items.update((list) => [...list, 'c']). The new reference differs from the old one, so the signal stores it and the template re-renders with 3.
Exercise
A service has readonly count = signal(0). You want components to read the count but only change it through an add() method. Show the change to the service and say what type the public field has afterwards.
Show answer
Make the writable signal private and expose a read-only view: private readonly _count = signal(0); readonly count = this._count.asReadonly(); add() { this._count.update((c) => c + 1); }. The public count has type Signal<number>, so cart.count.set(1) no longer compiles, while cart.count() still works in templates.