Sub topic 11
Resettable State with linkedSignal()
Some state is derived from other state and still has to be writable. A dropdown's selected item is a common case. It should default to the first option, the user should be able to pick a different one, and when the list of options changes the selection should reset or adjust. computed() can't do this because it is read-only. A plain signal() can't do it either, because it doesn't know when the options change. linkedSignal() handles this case.
This chapter assumes you know writable signals, computed(), and effect() from the earlier chapters, and that you can read Angular control-flow templates (@for). linkedSignal was added in Angular 19 as a developer preview and became stable in Angular 20.
The problem linkedSignal solves
Before linkedSignal, developers usually solved this with a writable signal plus an effect that resets it:
import { Component, effect, signal } from '@angular/core';
@Component({ selector: 'app-sizes-old', template: '' })
export class SizesOldComponent {
sizes = signal(['small', 'medium', 'large']);
selected = signal('small');
constructor() {
// Anti-pattern: syncing state with an effect
effect(() => {
this.selected.set(this.sizes()[0]);
});
}
}This works, but it has costs:
- Timing gap. Effects run later, during change detection. Between the moment
sizeschanges and the moment the effect runs,selectedholds a stale value that may not be in the list at all. Anything that readsselected()in that window sees inconsistent state. - Extra work. The update takes two passes: the view renders with the stale value, then the effect writes, then the view renders again.
- Hidden coupling. The relationship between
sizesandselectedsits in a constructor, away from the declaration ofselected.
linkedSignal declares the relationship in one place and computes the new value synchronously, the same way computed does. No reader can ever see the stale value.
The shorthand form
The simplest form takes a computation function, like computed:
import { linkedSignal, signal } from '@angular/core';
const sizes = signal(['small', 'medium', 'large']);
const selected = linkedSignal(() => sizes()[0]);
console.log(selected()); // 'small'
selected.set('large'); // user override
console.log(selected()); // 'large'
sizes.set(['xs', 's', 'm']); // source changed
console.log(selected()); // 'xs'selected is a WritableSignal<string>, so it has set(), update(), and asReadonly() like any writable signal. It behaves as follows:
- On first read, it runs the computation and caches the result.
- Calling
set()orupdate()replaces the cached value. The override lasts until something it depends on changes. - When any signal read inside the computation changes, the next read throws away the override and runs the computation again.
As with computed, evaluation is lazy and memoized. Changing sizes only marks selected as stale. The computation runs when someone reads selected().
The object form: source, computation, and previous
The shorthand always resets to a fresh value. Often you want something smarter, such as keeping the user's choice if it still exists in the new list. The object form gives the computation access to the previous state:
import { Component, linkedSignal, signal } from '@angular/core';
interface ShippingOption {
id: string;
label: string;
}
@Component({
selector: 'app-shipping',
template: `
@for (opt of options(); track opt.id) {
<label>
<input
type="radio"
name="shipping"
[checked]="opt.id === selected().id"
(change)="selected.set(opt)"
/>
{{ opt.label }}
</label>
}
<p>Selected: {{ selected().label }}</p>
<button (click)="dropStandard()">Remove standard</button>
`,
})
export class ShippingComponent {
options = signal<ShippingOption[]>([
{ id: 'std', label: 'Standard' },
{ id: 'exp', label: 'Express' },
{ id: 'ovn', label: 'Overnight' },
]);
selected = linkedSignal<ShippingOption[], ShippingOption>({
source: this.options,
computation: (newOptions, previous) =>
newOptions.find(o => o.id === previous?.value.id) ?? newOptions[0],
});
dropStandard() {
this.options.update(opts => opts.filter(o => o.id !== 'std'));
}
}The parts are:
| Property | Purpose |
|---|---|
| `source` | A signal, or a function that reads signals. Changes to it trigger recomputation. |
| `computation(source, previous)` | Returns the new value. Receives the current source value and the previous state. |
| `previous` | `undefined` on the first run. After that it is `{ source, value }`: the previous source value and the previous value of the linked signal, including a manual override. |
| `equal` | Optional equality function for the linked signal's own value, as with `signal()` and `computed()`. |
If the user picks Express and then Standard is removed, previous.value.id is 'exp'. Express is still in the list, so the selection stays. If the user had picked Standard, find returns undefined and the selection falls back to the first remaining option.
When you use the object form, give both generic parameters, linkedSignal<Source, Value>. TypeScript often can't infer Value from the computation alone, especially when previous is involved.
How it decides when to recompute
A linkedSignal is a reactive node with dependencies, like a computed. Recomputation is driven by its dependencies, which explains a few behaviours that can surprise you:
- Equal source values don't reset anything. If
options.set(sameArrayReference)is called, the signal's defaultObject.isequality treats it as unchanged, so the override survives. When you mutate an array in place and callsetwith the same reference, nothing resets. This is the same immutability rule as everywhere else in signals: replace arrays and objects, don't mutate them. - New references do reset, even with equal contents. If the source is a
computedthat builds a new array on every run, every upstream change counts as a source change. Give the source a customequalfunction if structurally identical lists shouldn't count as changes. - Reads inside the computation are tracked. In the shorthand form, every signal you read is a dependency. In the object form, keep dependency reads in
source. If the computation needs to read another signal without reacting to it, wrap that read inuntracked(). - Writes never flow back. Calling
selected.set()doesn't touchoptions. The link goes one way, from source to linked signal.
import { linkedSignal, signal, untracked } from '@angular/core';
const page = signal(1);
const pageSize = signal(20);
// Resets to the top when the page changes, but not when pageSize changes.
const scrollTop = linkedSignal<number, number>({
source: page,
computation: () => {
const size = untracked(() => pageSize());
return size > 50 ? 0 : 0; // placeholder for logic that uses size
},
});
scrollTop.set(400);
pageSize.set(100);
console.log(scrollTop()); // 400, pageSize is not a dependency
page.set(2);
console.log(scrollTop()); // 0, page changedChoosing between signal, computed, linkedSignal, and effect
| Need | Use |
|---|---|
| Independent state the user or code sets | `signal()` |
| Value fully determined by other signals, never set directly | `computed()` |
| Value derived from a source but can be overridden until the source changes | `linkedSignal()` |
| Pushing state outside the signal graph (DOM, storage, logging) | `effect()` |
A good rule: if you find yourself writing an effect whose only job is to call set() on another signal, replace it with linkedSignal or computed. Effects are for side effects, not for keeping signals in sync.
Common use cases
- Selections that depend on a list. Selected tab, selected row, chosen option. Reset or preserve the choice when the list changes.
- Form fields seeded from an input. A component receives
initialName = input('')and lets the user edit a local copy:name = linkedSignal(() => this.initialName()). If the parent passes a new value, the local edit is replaced. - Pagination. Reset
pageto 1 whenever the search query or filter changes, while still letting the user page through results. - Drafts. Edit a local copy of a record and discard the draft when a different record is loaded.
Edge cases and gotchas
- Empty sources. In the shipping example,
newOptions[0]isundefinedwhen the list is empty, which breaks theShippingOptiontype and any template readingselected().label. Make the value typeShippingOption | undefinedand handle it in the template, or keep a sentinel option. - Reading inside a template before data exists. The computation runs on the first read, which is often during the first render. Make sure the source has a usable initial value.
- Exposing linked state from a service. Expose
selected.asReadonly()and provide a method that callsset, the same encapsulation pattern used for plain writable signals. - Not a replacement for
model().model()syncs a value between parent and child.linkedSignalkeeps a local value derived one way from a source. Choose by asking who owns the value.
Exercise
You have tabs = signal(['Overview', 'Details', 'Reviews']) and want activeTab to default to the first tab, allow the user to switch tabs, and keep the user's tab when tabs is replaced by a new array that still contains it. Write the declaration of activeTab.
Show answer
Use the object form so the computation can see the previous value: activeTab = linkedSignal<string[], string>({ source: tabs, computation: (newTabs, previous) => previous && newTabs.includes(previous.value) ? previous.value : newTabs[0] });. The shorthand linkedSignal(() => tabs()[0]) would always jump back to 'Overview' when tabs changes.
Exercise
A developer writes items = signal<string[]>(['a', 'b']) and selected = linkedSignal(() => items()[0]). They call selected.set('b'), then run items().push('c'); items.set(items());. What does selected() return, and why?
Show answer
It returns 'b'. The array was mutated in place and set again with the same reference, so the default Object.is equality sees no change. The linked signal is not marked stale and the manual override survives. Use items.update(list => [...list, 'c']) to create a new array, and the selection resets to 'a'.
Exercise
Why is linkedSignal preferred over a writable signal plus an effect that calls set() when the source changes?
Show answer
The linkedSignal recomputes synchronously and lazily when read, so no consumer sees a stale value between the source change and the reset. An effect runs later, during change detection, which leaves a window of inconsistent state and causes an extra render pass. The linkedSignal also declares the dependency next to the state instead of hiding it in a constructor.