Sub topic 10
linkedSignal for state that resets
This chapter assumes you know the basics from earlier chapters. You should be able to create writable signals with signal(), derive read-only values with computed(), and know why an effect should not be used to copy one signal into another. You should also be comfortable with signal inputs in components. linkedSignal() was added in Angular 19 and is stable from Angular 20, so check your version before using it.
The problem: derived state that the user can also edit
Some state depends on another signal but must also accept user changes. Consider a dropdown. The selected item should default to the first option, and the user can pick another one. When the list of options changes, the old selection may no longer exist, so it should reset.
computed() cannot do this. It is read-only, so it has no set() method. You could use a plain signal() for the selection and an effect() that resets it when the options change. That approach works, but it has three drawbacks:
- The reset happens after the effect runs, so there is a window where the selection is stale.
- The effect writes to a signal, which is the pattern the earlier chapter on choosing between computed, effect and event handlers warned against.
- The logic is split across two places, so a reader has to connect them.
linkedSignal() handles this case directly. It is a writable signal whose value is recomputed from a source whenever that source changes.
The shortcut form
The simplest form takes one function. It works like computed(), but the result is writable.
import { signal, linkedSignal } from '@angular/core';
const options = signal(['apple', 'banana', 'cherry']);
const selected = linkedSignal(() => options()[0]);
console.log(selected()); // 'apple'
selected.set('banana');
console.log(selected()); // 'banana'
options.set(['kiwi', 'lime']);
console.log(selected()); // 'kiwi'Reading selected() first gives the default, 'apple'. Calling set() overrides it. When options changes, the signal discards the manual value and runs the function again, so the selection resets to 'kiwi'.
A linkedSignal has the same methods as a writable signal: set(), update() and asReadonly(). It also behaves like a computed signal in these ways:
- It is lazy. The function does not run until the first read.
- It is memoized. Repeated reads return the stored value without recalculating.
- It tracks the signals it read as dependencies.
The explicit form: source and computation
The shortcut form has a limit. Any signal read inside the function becomes a trigger for reset, and the function cannot see the old value. The explicit form separates these two concerns.
import { signal, linkedSignal } from '@angular/core';
interface Option {
id: number;
label: string;
}
const options = signal<Option[]>([
{ id: 1, label: 'Small' },
{ id: 2, label: 'Medium' },
{ id: 3, label: 'Large' },
]);
const selected = linkedSignal<Option[], Option | undefined>({
source: options,
computation: (newOptions, previous) => {
const kept = newOptions.find((o) => o.id === previous?.value?.id);
return kept ?? newOptions[0];
},
});
selected.set({ id: 2, label: 'Medium' });
// The list is reloaded and still contains id 2, so the selection survives.
options.set([
{ id: 2, label: 'Medium' },
{ id: 4, label: 'Extra large' },
]);
console.log(selected()?.id); // 2
// The list changes again and no longer contains id 2, so the selection resets.
options.set([{ id: 5, label: 'Tiny' }]);
console.log(selected()?.id); // 5The two properties do different jobs:
sourceis a function (here, a signal) that the linked signal watches. A change in its value triggers the computation.computationreceives the new source value and an optionalpreviousobject.previoushas two fields:source, the earlier source value, andvalue, the earlier value of the linked signal. On the first evaluation,previousisundefined.
The previous.value field is the value that was current before the source changed. If the user called set(), this is the user's value. That is what lets the example above keep a selection when it is still valid.
The generic types are linkedSignal<SourceType, ValueType>. Writing them out is useful when the computation can return undefined, as it does here.
A component example
Signal inputs are a common source. A product page shows a quantity picker, and the quantity should return to 1 when the product changes.
import { Component, input, linkedSignal } from '@angular/core';
@Component({
selector: 'app-quantity-picker',
template: `
<button (click)="decrement()" [disabled]="quantity() <= 1">-</button>
<span>{{ quantity() }}</span>
<button (click)="increment()">+</button>
`,
})
export class QuantityPickerComponent {
productId = input.required<number>();
quantity = linkedSignal({
source: this.productId,
computation: () => 1,
});
increment() {
this.quantity.update((q) => q + 1);
}
decrement() {
this.quantity.update((q) => Math.max(1, q - 1));
}
}Here the computation ignores its arguments. The source is what matters: each new productId produces a new source value, and the computation then returns the default of 1. The user's clicks go through update() and affect only the current product.
Choosing between computed, linkedSignal and effect
| Need | Use | Why |
|---|---|---|
| A value that is always a pure function of other signals | `computed()` | Read-only, so nothing can drift from its source. |
| A value that starts from other signals but the user can change it | `linkedSignal()` | Writable, and resets when its source changes. |
| Sending a value outside the signal graph (logging, storage, a third-party library) | `effect()` | Effects are for side effects, not for producing state. |
| Reacting to a single user action | Event handler | The action has a clear moment in time, so no signal reaction is needed. |
A quick test: if you can describe the value as "the default is X, but the user can override it," it is a linkedSignal. If you cannot imagine calling set() on it, use computed().
Equality and when the reset happens
Two rules control when a reset actually occurs.
- The source must change by equality. Signals compare values with
Object.isby default. If the source recomputes to an equal value, the linked signal is not reset. A source that returns a new array each time (for example from.filter()) will reset on every change, even when the contents are the same. Use acomputed()with a customequalfunction as the source if you need to avoid this. - The linked signal can have its own
equaloption. It decides whether a new computed value counts as a change for consumers. It works the same way as theequaloption oncomputed().
import { signal, linkedSignal } from '@angular/core';
const tags = signal(['a', 'b']);
const selectedTags = linkedSignal<string[], string[]>({
source: tags,
computation: (current) => [...current],
equal: (a, b) => a.length === b.length && a.every((v, i) => v === b[i]),
});Because of the equal function, a reset that produces the same contents does not notify templates or effects that read selectedTags.
Gotchas
- Put every reset trigger in
source. In the explicit form, treatsourceas the single list of things that cause a reset. Do not rely on signals read insidecomputationto behave as triggers or to be ignored. If you need a value in the computation without making it a trigger, wrap the read inuntracked(), as covered earlier in this tutorial. - A reset overwrites user input. There is no confirmation step. If losing the user's choice would be harmful, use the explicit form and return
previous.valuewhen it is still valid. - It is lazy. If nothing reads the linked signal, the computation does not run. A
set()call before any read still works. The stored value is used until the source changes. - Do not write to it from an effect to mimic a source. If you find yourself writing an effect that calls
set()on a linked signal, move that dependency intosourceinstead. - It is not a deep-state tool.
linkedSignalresets the whole value. For a form with many fields, use one linked signal per field or one object, and decide deliberately which source resets which part.
Summary
linkedSignal() sits between computed() and signal(). It derives a default from a source, accepts set() and update(), and recomputes whenever the source changes. The shortcut form is enough when the whole function is the source. The explicit form with source and computation gives you the previous value, so you can keep a still-valid choice. Prefer it over an effect that writes a signal, and prefer computed() whenever the value does not need to be writable.
Exercise
A page has a signal pageSize and a signal currentPage. The current page must go back to 1 whenever pageSize changes, but the user can move to other pages with next and previous buttons. Write the declaration of currentPage using linkedSignal and say why it is better than a signal plus an effect.
Show answer
currentPage = linkedSignal({ source: this.pageSize, computation: () => 1 }); (or the shortcut linkedSignal(() => { this.pageSize(); return 1; })). The buttons call currentPage.update(...). It is better than a signal plus an effect because the reset is declared next to the value, it happens when the value is read instead of after an effect runs, and it avoids an effect that writes to a signal.
Exercise
A linkedSignal named selectedId has source: this.items (a signal holding an array of objects with an id field). After items changes, you want to keep the user's selected id if an item with that id still exists, and otherwise fall back to the first item's id. What does the computation need that the shortcut form cannot provide, and how do you handle the very first run?
Show answer
The computation needs the previous value, which only the explicit form provides through its second argument, previous.value. On the first run previous is undefined, so use optional chaining (previous?.value). Return the previous id when newItems.some(i => i.id === previous?.value) is true, and otherwise return newItems[0]?.id.