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 event bindings. It covers the three operations you use most: creating a signal with signal(), replacing its value with set(), and changing it based on its current value with update().
The working model
A writable signal is a wrapper around a value. You read the value by calling the signal like a function. You change the value through methods on the signal. Each read inside a reactive context, such as a template, computed(), or effect(), records a dependency. Each write tells those dependents that the value changed.
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()); // 6TypeScript infers the type from the initial value, so signal(0) is a WritableSignal<number>. When the initial value is narrower than what you plan to store, pass the type explicitly: signal<string | null>(null).
set() versus update()
| Method | Use when | Example |
|---|---|---|
| `set(value)` | The new value does not depend on the old one | `name.set('Ada')` |
| `update(fn)` | The new value is computed from the old one | `count.update(c => c + 1)` |
update() is shorthand for set(fn(current())), but it states your intent more clearly and keeps the read and the write together.
Using signals in a component
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-todo',
template: `
<input #box (keyup.enter)="add(box.value); box.value = ''" />
<p>{{ todos().length }} items</p>
<ul>
@for (todo of todos(); track $index) {
<li>{{ todo }}</li>
}
</ul>
<button (click)="clear()">Clear</button>
`,
})
export class TodoComponent {
todos = signal<string[]>([]);
add(text: string) {
if (!text.trim()) return;
this.todos.update(list => [...list, text.trim()]);
}
clear() {
this.todos.set([]);
}
}The template calls todos() to read the signal, so Angular knows this view depends on it and refreshes the view when it changes.
How a write propagates
By default a signal compares old and new values with Object.is. For objects and arrays, that means comparing references.
Common errors
Mutating objects in place
// Wrong: same array reference, so no dependents are notified
this.todos().push('milk');
// Wrong: update returns the same reference
this.todos.update(list => { list.push('milk'); return list; });
// Right: new array, new reference
this.todos.update(list => [...list, 'milk']);Forgetting the parentheses
Writing {{ todos.length }} in a template reads a property of the signal function, not the array. Always call the signal: {{ todos().length }}. In TypeScript, if (this.isOpen) is always truthy because a function is truthy. Write if (this.isOpen()).
Exposing write access too widely
Any code that holds a WritableSignal can change it. To share a signal without letting others write to it, expose asReadonly():
private readonly _count = signal(0);
readonly count = this._count.asReadonly(); // Signal<number>, no set/updateExercise
A component holds user = signal({ name: 'Ada', age: 36 }). A method runs this.user().age = 37; and the template, which shows {{ user().age }}, does not update. Why, and what is the correct code?
Show answer
The method mutates the existing object without calling set() or update(), so the signal never learns that anything changed and no dependents are notified. Even if it called update() and returned the same object, Object.is would treat the old and new values as equal. Replace the object instead: this.user.update(u => ({ ...u, age: 37 }));
Exercise
Which method fits each case: (a) resetting a form field to an empty string, (b) toggling a boolean isOpen signal?
Show answer
(a) field.set(''), because the new value does not depend on the old one. (b) isOpen.update(open => !open), because the new value is derived from the current one.