Sub topic 6
Holding task state in signals
This chapter assumes you can read TypeScript, you have the Task interface from the earlier chapter, and you have a standalone component that renders a list. It covers how to hold the task list in a signal, derive values from it, and update it safely.
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. You change it with set() or update().
import { signal } from '@angular/core';
const count = signal(0);
console.log(count()); // 0
count.set(5);
count.update(n => n + 1);
console.log(count()); // 6The call count() does more than return a value. When code runs inside a template, a computed, or an effect, the read registers that code as a dependent of the signal. When the signal changes, Angular knows which templates and derived values to refresh. This is how signals differ from plain class fields, where Angular has to check every component to find out what changed.
Putting the task list in a signal
The task list is an array of Task objects, so the signal's type is Task[]. Give it an explicit type parameter and an empty array as the starting value. Without the parameter, TypeScript infers never[] and rejects every later update.
import { signal } from '@angular/core';
import { Task } from './task';
const tasks = signal<Task[]>([]);In a template you read it with parentheses, the same way as in code:
@for (task of tasks(); track task.id) {
<li>{{ task.title }}</li>
}Leaving off the parentheses is a common mistake. tasks is the signal object, and tasks() is the array.
Updating state by replacement
A signal notifies its dependents only when its value changes, and it decides that with Object.is. For an array, that means a new array reference. Pushing into the existing array leaves the reference the same, so nothing updates.
import { signal } from '@angular/core';
import { Task } from './task';
const tasks = signal<Task[]>([]);
// Wrong: mutates the array in place. The reference is unchanged,
// so the signal reports no change and the view does not refresh.
tasks().push({ id: 1, title: 'Write chapter', done: false });
// Right: build a new array and hand it to the signal.
tasks.update(list => [...list, { id: 2, title: 'Review chapter', done: false }]);The same rule applies to the objects inside the array. To toggle a task, create a new object for that task and reuse the others:
tasks.update(list =>
list.map(t => (t.id === 2 ? { ...t, done: !t.done } : t))
);Reusing the untouched objects is deliberate. Their references stay the same, which lets @for with track task.id keep the existing DOM elements for those rows and re-render only the one that changed.
The three operations the task list needs follow one pattern:
| Operation | Update expression | Result |
|---|---|---|
| Add | `[...list, newTask]` | New array with one more item |
| Toggle | `list.map(t => t.id === id ? { ...t, done: !t.done } : t)` | New array, one new object |
| Remove | `list.filter(t => t.id !== id)` | New array without the item |
Use set() when the new value does not depend on the old one, such as clearing the list with tasks.set([]). Use update() when it does. update() receives the current value, so you never have to read the signal separately and risk acting on a stale copy.
Deriving values with computed
The "remaining" count is a function of the task list. Do not store it in a second signal that you must remember to keep in sync. Declare it with computed():
import { computed, signal } from '@angular/core';
import { Task } from './task';
const tasks = signal<Task[]>([
{ id: 1, title: 'Write chapter', done: true },
{ id: 2, title: 'Review chapter', done: false },
]);
const remaining = computed(() => tasks().filter(t => !t.done).length);
console.log(remaining()); // 1
tasks.update(list => list.map(t => ({ ...t, done: true })));
console.log(remaining()); // 0A computed signal has three properties worth knowing:
- It is lazy. The function does not run until something reads
remaining(). - It is memoized. The result is cached, and the function runs again only after a signal it read has changed.
- It tracks dependencies dynamically. Only the signals actually read during the last run count as dependencies. If a branch of your function does not run, the signals in that branch are not tracked.
A computed signal is read-only. Calling remaining.set(3) is a compile error. That is the point: the value can only come from its source signals.
The computed function must be pure. Do not change other signals or call the service's add() inside it. Angular reports an error if a computed function writes to a signal.
The data flow
Notice that nothing in this chain calls a "refresh" method. You change the signal, and the reads inside templates do the rest.
Exposing state without exposing control
Once the signal lives in a service, any component that injects the service could call set() on it. That makes it hard to know where a change came from. The pattern used in this tutorial keeps the writable signal private and exposes a read-only view:
import { Injectable, computed, signal } from '@angular/core';
import { Task } from './task';
@Injectable({ providedIn: 'root' })
export class TaskService {
private readonly _tasks = signal<Task[]>([]);
private nextId = 1;
readonly tasks = this._tasks.asReadonly();
readonly remaining = computed(() => this._tasks().filter(t => !t.done).length);
add(title: string): void {
this._tasks.update(list => [...list, { id: this.nextId++, title, done: false }]);
}
toggle(id: number): void {
this._tasks.update(list => list.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
}
remove(id: number): void {
this._tasks.update(list => list.filter(t => t.id !== id));
}
}asReadonly() returns a signal that you can read and track but not write. Components see tasks() and remaining(), and the only way to change state is through add, toggle, and remove. Any rule you later add, such as rejecting empty titles, goes in one place.
The next chapter covers the service and dependency injection in detail. Here the focus is the state inside it.
Reacting to changes with effect
Sometimes you need a side effect when state changes, such as writing to localStorage or logging. That is what effect() is for. An effect runs once when it is created and again whenever a signal it read changes.
import { Component, effect, inject } from '@angular/core';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-logger',
template: `<p>{{ service.remaining() }} remaining</p>`,
})
export class TaskLoggerComponent {
protected readonly service = inject(TaskService);
constructor() {
effect(() => {
console.log(`Tasks: ${this.service.tasks().length}`);
});
}
}An effect must be created in an injection context, which in practice means a constructor or a field initializer. Angular uses that context to destroy the effect when the component is destroyed.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| List does not update after adding an item | The array was mutated with `push`, `splice`, or `sort` | Replace the array with `update` and a spread, `map`, or `filter` |
| Template shows `[Getter]` or a function body | The signal was read without calling it | Write `tasks()` instead of `tasks` |
| `never` type errors on update | `signal([])` was used without a type parameter | Write `signal<Task[]>([])` |
| Toggle changes the wrong row, or every row re-renders | Task objects were mutated, or `track` uses the wrong key | Spread the changed task into a new object and use `track task.id` |
| Error about writing to a signal in a computed | A side effect was placed inside `computed()` | Move the write into a service method or an event handler |
| `Property 'set' does not exist` on the service signal | The signal was exposed with `asReadonly()` or is a `computed` | Add a method on the service that performs the update |
Checking your work
To confirm the pattern works in practice, add a few tasks through the service and toggle one. The "remaining" paragraph in TaskListComponent should change without any code that refreshes the view. If the list stays stale, look for in-place mutation first. It is the most common cause by a wide margin.
Exercise
A teammate writes toggle(id) as const t = this._tasks().find(t => t.id === id); if (t) t.done = !t.done;. The checkbox state in the browser changes, but the "remaining" count does not. Explain why, and rewrite the method.
Show answer
The method mutates the task object in place, so the array reference held by the signal never changes. The signal sees the same value under Object.is, so it does not notify, and the remaining computed keeps its cached result. The checkbox looks right only because the browser toggled it itself. The fix is to replace the array and the changed object: this._tasks.update(list => list.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
Exercise
Add a completed computed value to TaskService that returns the number of finished tasks. Why is this better than a separate completed signal that toggle() updates?
Show answer
Add readonly completed = computed(() => this._tasks().filter(t => t.done).length);. A computed value is derived from _tasks, so it cannot disagree with the list, and every method that changes the list is covered automatically. A separate signal would have to be updated in add, toggle, and remove, and forgetting one of them would leave the two values out of sync.