Sub topic 2
Creating and Updating Writable Signals
This chapter assumes you know TypeScript generics and arrow functions, and that you can build an Angular component with a template and data binding. The previous chapter explained why Angular moved toward fine-grained reactivity. This one covers the basic building block: the writable signal. You will learn how to create one, read it, change it with set() and update(), and avoid the mistakes that cause silent bugs.
What a writable signal is
A writable signal is a wrapper around a value. You read the value by calling the signal as a function, and you change it through methods on the signal. Every read happens through a function call, so Angular knows who read the value. Every write goes through a method, so Angular knows when the value changed. A plain class property gives Angular neither piece of information.
You create a writable signal with the signal() function from @angular/core:
import { signal, WritableSignal } from '@angular/core';
const count: WritableSignal<number> = signal(0);
console.log(count()); // 0
count.set(5);
console.log(count()); // 5
count.update(c => c + 1);
console.log(count()); // 6This code runs anywhere Angular's core package is loaded. Unlike effect(), signal() does not need an injection context, so you can create signals in services, in plain functions, in tests, or at module level.
The type of a signal
signal(0) infers WritableSignal<number>. When TypeScript cannot infer the type you want from the initial value, pass a type argument:
import { signal } from '@angular/core';
interface User { id: number; name: string; }
const status = signal<'idle' | 'loading' | 'error'>('idle');
const user = signal<User | null>(null);
const tags = signal<string[]>([]);Without the type argument, signal(null) would be typed WritableSignal<null>, and you could never store a user in it. signal([]) would be WritableSignal<never[]>. Annotate empty or nullable initial values every time.
A WritableSignal<T> extends Signal<T>, the read-only type. The read-only type has only the call signature. The writable type adds set(), update(), and asReadonly().
The three operations
| Operation | Signature | Use it when |
|---|---|---|
| Read | `sig()` | You need the current value |
| `set` | `sig.set(value: T): void` | The new value does not depend on the old one |
| `update` | `sig.update(fn: (value: T) => T): void` | The new value is computed from the old one |
| `asReadonly` | `sig.asReadonly(): Signal<T>` | You want to hand out a signal that callers cannot write |
update(fn) is shorthand for set(fn(current)). It does not batch, defer, or merge anything. It exists because "take the old value and produce a new one" is the most common write, and the callback form keeps the read and write in one expression.
Using signals in a component
Here is the standard counter. The computed() line is covered in the next chapter. For now, notice how the template calls count() and how the methods change it.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<p>Count: {{ count() }} (double: {{ double() }})</p>
<button (click)="increment()">+1</button>
<button (click)="reset()">Reset</button>
`,
})
export class CounterComponent {
count = signal(0);
double = computed(() => this.count() * 2);
increment() {
this.count.update(c => c + 1);
}
reset() {
this.count.set(0);
}
}When the template reads count(), Angular records the template as a consumer of that signal. When increment() runs, the signal tells its consumers they are out of date, and Angular schedules the view to refresh. A later chapter explains how this interacts with OnPush and zoneless change detection.
What happens on a write
A write does not push the new value to anyone. It marks dependents as dirty, and they pull the new value the next time they are read.
The equality check matters most. By default Angular compares with Object.is. For numbers, strings, and booleans this means "same value". For objects and arrays it means "same reference". That one rule causes most of the mistakes intermediate developers make with signals.
Immutability: the most common error
Look at this code:
import { signal } from '@angular/core';
const items = signal<string[]>(['apple']);
// Wrong: mutates the array in place
items.update(list => {
list.push('banana');
return list;
});The callback returns the same array reference it received. Object.is(old, new) is true, so the signal considers nothing changed and notifies nobody. The array now holds two items, but any template showing items().length still shows 1 until something else triggers a refresh. The bug is intermittent, which makes it hard to track down.
Always produce a new reference:
import { signal } from '@angular/core';
interface Todo { id: number; title: string; done: boolean; }
const items = signal<string[]>(['apple']);
items.update(list => [...list, 'banana']); // add
items.update(list => list.filter(i => i !== 'apple')); // remove
const todo = signal<Todo>({ id: 1, title: 'Write docs', done: false });
todo.update(t => ({ ...t, done: true })); // change one field
const todos = signal<Todo[]>([todo()]);
todos.update(list =>
list.map(t => (t.id === 1 ? { ...t, title: 'Ship docs' } : t))
); // change one itemThe reverse problem also exists. If you call set() with a new object whose contents match the old one, the reference differs, so consumers are notified even though nothing meaningful changed. That is usually harmless, since it only costs a re-render. When it matters, a custom equality function fixes it. That option is covered in the chapter on equality and untracked().
Nested mutation through a read
Calling the signal returns the stored value itself, not a copy. So this also mutates state behind the signal's back:
import { signal } from '@angular/core';
const settings = signal({ theme: 'light', fontSize: 14 });
settings().fontSize = 18; // compiles, but no consumer is notifiedTypeScript allows it because the value is a normal object. To block it at compile time, type the signal with Readonly<T> or ReadonlyArray<T>:
import { signal } from '@angular/core';
interface Settings { theme: 'light' | 'dark'; fontSize: number; }
const settings = signal<Readonly<Settings>>({ theme: 'light', fontSize: 14 });
// settings().fontSize = 18; // error: fontSize is read-only
settings.update(s => ({ ...s, fontSize: 18 })); // fineExposing read-only signals
A component or service often owns some state and wants others to read it but not write it. asReadonly() returns a Signal<T> view that tracks the same value and has no set() or update():
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class SessionStore {
private readonly _userName = signal<string | null>(null);
readonly userName = this._userName.asReadonly();
login(name: string) {
this._userName.set(name);
}
logout() {
this._userName.set(null);
}
}Consumers call store.userName() and react to changes. They cannot write it, because the type has no write methods. The chapter on signal-based services builds this pattern into a full store.
Where you can and cannot write
Writes are allowed in event handlers, service methods, lifecycle hooks, setTimeout callbacks, and subscription callbacks. Since Angular 19 you can also write inside effect() without extra flags. The older allowSignalWrites option is deprecated and has no effect.
Writes are forbidden inside computed(). A computed signal must be a pure derivation, so Angular throws an error if you call set() or update() on any signal while a computed is evaluating. Writing during template evaluation is also an error, for the same reason. If you find yourself wanting to write inside a derivation, you probably want linkedSignal() or an effect. Both are covered later.
Common errors at a glance
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| Template shows `[Function]` or a function's source | Wrote `{{ count }}` instead of `{{ count() }}` | Call the signal | |
| UI does not update after adding to a list | `push` and returned the same array | Return `[...list, item]` | |
| UI does not update after editing a field | Mutated `sig().field` directly | `update(v => ({ ...v, field }))` | |
| `Argument of type 'User' is not assignable to 'null'` | `signal(null)` inferred type `null` | `signal<User \ | null>(null)` |
| Error thrown about writes in a reactive context | Called `set()` inside `computed()` | Move the write to a handler, effect, or `linkedSignal` | |
| `mutate is not a function` | Code written for Angular 16 | Use `update()` with immutable updates |
Exercises
Exercise
A component has selected = signal<number[]>([]) and a method toggle(id: number). Write the body of toggle so it adds id if it is absent and removes it if present, in a way that consumers are always notified.
Show answer
this.selected.update(ids => ids.includes(id) ? ids.filter(x => x !== id) : [...ids, id]); Both branches return a new array (filter creates one, the spread creates one), so the Object.is check sees a new reference and notifies consumers.
Exercise
Given const n = signal(3);, how many times are consumers notified by n.set(3); n.update(v => v); n.set(4);, and why?
Show answer
Once. The first two writes produce the value 3, and Object.is(3, 3) is true, so the signal ignores them. Only set(4) changes the value, increments the version, and marks consumers dirty.
Exercise
Why is readonly total = this._total.asReadonly() safer than readonly total = this._total in a service, even though both fields are marked readonly?
Show answer
The readonly keyword only stops the field from being reassigned. this._total is still a WritableSignal, so callers could run service.total.set(...). asReadonly() returns a Signal<T> with no write methods, so outside code can only read it.