Sub topic 6
Holding task state in signals
This chapter assumes you have the Task interface from the earlier chapter and a standalone component that renders a list. You should be comfortable with TypeScript generics and arrow functions.
What a signal is
A signal is a wrapper around a value that tells Angular when the value changes. You read it by calling it like a function. Any template or computed value that reads a signal is updated automatically when the signal changes.
import { signal } from '@angular/core';
import { Task } from './task';
const tasks = signal<Task[]>([]);
console.log(tasks()); // []The generic signal<Task[]> fixes the type of the value. The argument is the starting value.
Changing a signal
A signal has two ways to write a new value:
set(value)replaces the value.update(fn)computes the new value from the current one.
tasks.set([{ id: 1, title: 'Learn signals', done: false }]);
tasks.update(list => [...list, { id: 2, title: 'Add a form', done: false }]);Signals decide whether something changed by comparing the old and new value with Object.is. If you mutate an array in place, the reference stays the same and Angular sees no change.
// Wrong: same array reference, so nothing updates
tasks().push({ id: 3, title: 'Broken', done: false });
// Right: a new array
tasks.update(list => [...list, { id: 3, title: 'Works', done: false }]);Updating one item follows the same rule. Use map and copy the changed object with a spread:
tasks.update(list => list.map(t => (t.id === 1 ? { ...t, done: !t.done } : t)));Derived values with computed
The number of unfinished tasks depends on the task list. Do not store it in a second signal that you must keep in sync. Use computed, which derives a read-only value from other signals.
import { Component, computed, signal } from '@angular/core';
import { Task } from './task';
@Component({
selector: 'app-task-counter',
template: `
<button type="button" (click)="addSample()">Add</button>
<p>{{ remaining() }} of {{ tasks().length }} remaining</p>
`,
})
export class TaskCounterComponent {
readonly tasks = signal<Task[]>([]);
readonly remaining = computed(() => this.tasks().filter(t => !t.done).length);
private nextId = 1;
addSample(): void {
this.tasks.update(list => [
...list,
{ id: this.nextId++, title: `Task ${this.nextId - 1}`, done: false },
]);
}
}A computed value is lazy and cached. It runs its function the first time something reads it. It runs again only after a signal it read has changed.
Keeping writes under control
A public writable signal lets any code replace the whole list. The service in the next chapter avoids this. It keeps the writable signal private and exposes a read-only view with asReadonly():
private readonly _tasks = signal<Task[]>([]);
readonly tasks = this._tasks.asReadonly();Callers can read tasks() but have no set or update. They have to go through methods such as add and toggle.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| The template shows `[object Object]` or a function | You wrote `{{ tasks }}` | Call it: `{{ tasks() }}` |
| The list does not update after a push | You mutated the array in place | Use `update` with a new array |
| A computed value seems stale | It reads a plain field, not a signal | Store that field in a signal |
| A type error on `set` | The value does not match `Task[]` | Fix the object shape or the generic |
Exercise
Exercise
A component holds items = signal<string[]>([]). A teammate writes this.items().push('milk') and the page does not change. Why, and what is the fix?
Show answer
push mutates the existing array, so the signal's value keeps the same reference and Angular sees no change. Replace the array instead: this.items.update(list => [...list, 'milk']).