# Angular Signals — Migration Guide

## Table of contents

- [Overview](angular-signals#overview)
- [Core primitives](angular-signals#core_primitives)
- [computed()](angular-signals#_code_computed____code_)
- [effect()](angular-signals#_code_effect____code_)
- [untracked()](angular-signals#_code_untracked____code_)
- [linkedSignal()](angular-signals#_code_linkedsignal____code_)
- [input() and model()](angular-signals#_code_input____code__and__code_model____code_)
- [viewChildren() and viewChild()](angular-signals#_code_viewchildren____code__and__code_viewchild____code_)
- [Mental model — computed() vs effect()](angular-signals#mental_model____code_computed____code__vs__code_effect____code_)
- [Migration patterns](angular-signals#migration_patterns)
- [Inheritance caveat](angular-signals#inheritance_caveat)
- [Testing signals](angular-signals#testing_signals)
- [Common pitfalls](angular-signals#common_pitfalls)

---

## Overview

Angular Signals are a reactive primitive introduced to replace zone-based
change detection with a fine-grained, declarative reactivity model.
The goal is to make data flow explicit, predictable, and performant.

```ts
import { signal, computed, effect, untracked } from '@angular/core';
```

---

## Core primitives

### `signal()`

A writable reactive value. Reading it inside a reactive context (template,
`computed`, `effect`) creates a dependency automatically.

```ts
readonly count = signal(0);

increment(): void {
  this.count.update(v => v + 1);
  // or
  this.count.set(5);
}
```

| Method        | Description                    |
| ------------- | ------------------------------ |
| `.set(value)` | Replace the value              |
| `.update(fn)` | Derive next value from current |

> ⚠️ `.mutate()` is **not** part of the public API. It was part of the
> original signals proposal but was removed from `WritableSignal` before
> the stable release — mutating an object without a `.set()`/`.update()`
> call is invisible to the signal graph. Always produce a new reference
> via `.update()` (see [pitfall #8](angular-signals#common_pitfalls)).

---

## `computed()`

A **read-only derived signal**. Re-evaluates only when one of its dependencies
changes. Lazy and memoized.

```ts
readonly minYear = computed(() => this.minDate()?.[0] ?? dayjs().year() - 100);
readonly fullName = computed(() => `${this.firstName()} ${this.lastName()}`);
readonly isValid = computed(() => this.value() >= this.min() && this.value() <= this.max());
```

### Rules

- Pure and synchronous — no side effects
- Never call `.set()` inside a `computed()`
- Dependencies are tracked automatically — no need to declare them

### When `computed()` replaces imperative code

Before — manual update in a setter:

```ts
@Input()
set minDate(value: number[]) {
  this._minDate = value;
  if (value?.length) {
    this.minYear = value[0]; // manual sync
  }
}
```

After — declarative derivation:

```ts
readonly minDate = input<number[]>();
readonly minYear = computed(() => this.minDate()?.[0] ?? dayjs().year() - 100);
```

---

## `effect()`

Runs a **side effect** whenever its signal dependencies change.
Use it to synchronize signals with the outside world.

```ts
effect(() => {
    localStorage.setItem('theme', this.theme());
});

effect(() => {
    this.externalHelper.value = this.mySignal();
});
```

### Rules

- Runs at least once on initialization
- Avoid calling `.set()` on signals inside an effect — use `computed()` instead
- Registered in the constructor injection context by default
- Cleaned up automatically when the component is destroyed
- Only signals read **without** `untracked()` become dependencies — see
  [`untracked()`](angular-signals#_code_untracked____code_) below for reading
  a signal inside an effect without subscribing to it

### Tracking the previous value

`effect()` does not provide a previous value out of the box.
Use a plain class field to capture it:

```ts
private previousIsVisible = false;

private readonly visibilityEffect = effect(() => {
  const current = this.isVisible();
  const previous = this.previousIsVisible;

  if (!previous && current) {
    this.onOpen();
  }

  this.previousIsVisible = current;
});
```

---

## `untracked()`

`untracked()` lets you read a signal's value **inside a reactive context**
(`effect()`, `computed()`) **without** registering it as a dependency.
This is the main tool for controlling exactly which signals an `effect()`
reacts to, when the effect's body needs to read more state than it should
actually react to.

```ts
import { untracked } from '@angular/core';

effect(() => {
    const id = this.userId(); // tracked — effect re-runs when this changes
    const config = untracked(() => this.appConfig()); // read, but not tracked

    this.analytics.logUserView(id, config);
});
```

### Why this matters

An `effect()` automatically tracks **every** signal it reads during its
synchronous execution. Sometimes that's too broad: you only want the effect
to re-run for a subset of the signals it touches, and reading the rest is
just "give me the current value, don't subscribe me to it."

This is especially common when an effect needs to read the **same signal it
is about to write to** (directly or via a method that writes to it).
Reading it without `untracked()` can cause the effect to register itself as
its own dependency, leading to redundant re-runs or, in more complex chains,
an infinite loop.

```ts
// 🔴 Risky — `this.value()` is read in the same effect that may end up
// triggering a write back to `value`, depending on what updateNgModel does
effect(() => {
    this.showLine1();
    this.showLine2();

    const current = this.value(); // tracked unintentionally
    const sanitized = this.sanitize(current);

    if (sanitized !== current) {
        this.updateNgModel(sanitized); // writes back to `value`
    }
});

// 🟢 Safe — only the visibility signals are tracked;
// `value` is read but not subscribed to
effect(() => {
    this.showLine1();
    this.showLine2();

    const current = untracked(() => this.value());
    const sanitized = this.sanitize(current);

    if (sanitized !== current) {
        this.updateNgModel(sanitized);
    }
});
```

In the safe version, the effect's dependency list is exactly
`[showLine1, showLine2]`. Writing to `value` inside the effect body no longer
risks the effect re-triggering itself purely because it also happened to read
`value()` reactively.

### Other common uses

Reading a signal for one-off, non-reactive logic inside a `computed()`:

```ts
readonly summary = computed(() => {
  const items = this.items();
  // logging shouldn't be a reason for `summary` to be considered "stale"
  untracked(() => console.debug('recomputing summary', items.length));
  return items.length;
});
```

Calling an imperative API (router, third-party widget, focus management)
that internally reads signals, without wanting those internal reads to
become dependencies of your effect:

```ts
effect(() => {
    const open = this.isVisible();
    if (open) {
        untracked(() => this.focusManager.focusDefaultElement());
    }
});
```

### Rules

- `untracked()` does not prevent the read — it only prevents the
  **dependency tracking** of that read
- Use it when an effect or computed needs a signal's current value for
  logic, but should not re-run merely because that signal changed
- A frequent signal that you need `untracked()`: an `effect()` that reads
  and then conditionally writes back to the **same** signal — read the
  current value with `untracked()`, keep the write outside of it
- Do not reach for `untracked()` as a substitute for an equality check;
  it controls _what triggers_ the effect, not _whether the write is a no-op_.
  Combine both when guarding against redundant or looping writes

---

## `linkedSignal()`

A **writable signal** whose value resets automatically when a source signal
changes. It fills the gap between `computed()` (read-only) and `signal()`
(no automatic sync with a source).

```ts
import { linkedSignal } from '@angular/core';

readonly options = input<string[]>([]);

readonly selectedOption = linkedSignal(() => this.options()[0]);
```

Whenever `options` changes, `selectedOption` resets to the first item.
But the user (or the component) can still write to it in the meantime:

```ts
this.selectedOption.set('other value'); // works, until options changes again
```

---

### When to use `linkedSignal()`

| Scenario                                      | Tool             |
| --------------------------------------------- | ---------------- |
| Read-only derivation, never written locally   | `computed()`     |
| Local state that resets when a source changes | `linkedSignal()` |
| Two-way binding with parent                   | `model()`        |
| Independent local state                       | `signal()`       |

---

### Full form — source + computation

The short form `linkedSignal(() => source())` is sugar for the full form,
which gives you access to the **previous value** of the linked signal:

```ts
readonly selectedOption = linkedSignal<string[], string>({
  source: this.options,
  computation: (newOptions, previous) => {
    // If the previously selected option still exists in the new list, keep it
    if (previous && newOptions.includes(previous.value)) {
      return previous.value;
    }
    return newOptions[0];
  },
});
```

`previous` contains `{ source: S; value: D }` — the previous value of the
`source` signal **and** the previous value of the linked signal itself, or
`undefined` on first run. Explicit generic type arguments (`<S, D>`) are
required as soon as you use `previous`.

---

### Migration pattern — setter with local state reset

A common pattern before signals was a setter that reset local state
when an input changed:

```ts
// Before
private _options: string[] = [];
selectedOption: string;

@Input()
set options(value: string[]) {
  this._options = value;
  this.selectedOption = value[0]; // reset local selection
}
```

After — `linkedSignal()` expresses this declaratively:

```ts
// After
readonly options = input<string[]>([]);
readonly selectedOption = linkedSignal(() => this.options()[0]);
```

---

### Red flag — `effect()` resetting a `signal()`

If you find yourself writing an `effect()` that resets a plain `signal()`
when another signal changes, that is a `linkedSignal()` in disguise:

```ts
// 🔴 Bad
readonly selectedOption = signal('');

private readonly resetEffect = effect(() => {
  this.selectedOption.set(this.options()[0]);
});

// 🟢 What it really is
readonly selectedOption = linkedSignal(() => this.options()[0]);
```

---

## `input()` and `model()`

### `input()`

Replaces `@Input()` for one-way parent → child binding.

```ts
// Before
@Input() closeable = true;

// After
readonly closeable = input(true);
```

With a default value and a type:

```ts
readonly minYear = input<number>(dayjs().year() - 100);
```

### `model()`

Replaces `@Input()` + `@Output()` pairs for **two-way binding**.
Automatically creates the corresponding `Change` output.

```ts
// Before
@Input() isVisible = false;
@Output() isVisibleChange = new EventEmitter<boolean>();

// After
readonly isVisible = model(false);
```

Usage in a parent template:

```html
<!-- two-way -->
<my-component [(isVisible)]="open" />

<!-- one-way binding — compiles fine, but changes made by the -->
<!-- component are not propagated back to `open` -->
<my-component [isVisible]="open" />
```

> ⚠️ A one-way `[binding]` on a `model()` input is valid and compiles —
> it's up to the consumer to decide whether they use the input, the
> output, or both. It's just pointless if the component never needs to
> write back: use `input()` instead to communicate intent clearly.

> ⚠️ `model()` holds object values by reference. Mutating a nested property
> of a `model()`'s value (e.g. `this.address().locality.name = 'x'`) does
> **not** notify the signal or the parent binding. Always `.set()` or
> `.update()` with a new top-level reference:
> `this.address.update(current => ({ ...current, locality: newLocality }))`.

### Choosing between `input()` and `model()`

| Scenario                         | Tool         |
| -------------------------------- | ------------ |
| Parent writes, child only reads  | `input()`    |
| Parent writes, child writes back | `model()`    |
| Derived from other inputs        | `computed()` |

### `input()` with alias — ESLint caveat

If you need an internal name different from the public binding name,
use the `alias` option. Note that `@angular-eslint/no-input-rename` will
flag this — disable it locally only when strictly necessary:

```ts
// eslint-disable-next-line @angular-eslint/no-input-rename
readonly minYearInput = input<number>(dayjs().year() - 100, { alias: 'minYear' });
```

Prefer renaming the property to match the alias whenever possible.

---

## `viewChildren()` and `viewChild()`

Replaces `@ViewChildren` and `@ViewChild` with signal-based queries.

```ts
// Before
@ViewChildren('dayButtonElemRef') daysButtons: QueryList<ElementRef>;

// After
readonly daysButtons = viewChildren<ElementRef>('dayButtonElemRef');
```

The signal returns a `readonly T[]` — always guard against empty arrays:

```ts
const enabled = [...(this.daysButtons() ?? [])].filter(
    (el) => el.nativeElement.getAttribute('disabled') === null,
);
```

Reacting to changes — use `effect()`:

```ts
private readonly daysEffect = effect(() => {
  const buttons = this.daysButtons();
  if (buttons.length > 0) {
    this.changeDetector.detectChanges();
  }
  this.helper.buttons = buttons;
});
```

---

## Mental model — `computed()` vs `effect()`

> **"Am I calculating something, or am I doing something?"**

| Intent                    | Tool         |
| ------------------------- | ------------ |
| Transform data            | `computed()` |
| Derive state              | `computed()` |
| Synchronize with the DOM  | `effect()`   |
| Drive an external service | `effect()`   |
| Log, track                | `effect()`   |

### The red flag

If you find yourself writing an `effect()` that calls `.set()` on another signal,
it is almost always a `computed()` in disguise:

```ts
// 🔴 Bad — effect producing a value
effect(() => {
  this.minYear.set(this.minDate()?.[0] ?? dayjs().year() - 100);
});

// 🟢 What it really is
readonly minYear = computed(() => this.minDate()?.[0] ?? dayjs().year() - 100);
```

> 💡 If the effect genuinely needs to remain an `effect()` (e.g. it also
> performs a non-signal side effect like calling a service), but reads a
> signal purely for context rather than as a trigger, reach for
> [`untracked()`](angular-signals#_code_untracked____code_) instead of
> restructuring into a `computed()`.

---

## Migration patterns

### Pattern 1 — Simple `@Input()` → `input()`

```ts
// Before
@Input() id: string;

// After
readonly id = input<string>();
```

### Pattern 2 — `@Input()` with setter → `input()` + `computed()`

When the setter only derived a value:

```ts
// Before
@Input()
set minDate(value: number[]) {
  this._minDate = value;
  if (value?.length) this.minYear = value[0];
}

// After
readonly minDate = input<number[]>();
readonly minYear = computed(() => this.minDate()?.[0] ?? dayjs().year() - 100);
```

When the setter triggered side effects:

```ts
// Before
@Input()
set isVisible(val: boolean) {
  this._isVisible = val;
  this.isVisibleChange.emit(val);
  this.focusDefaultDay();
}

// After
readonly isVisible = model(false);

private readonly isVisibleEffect = effect(() => {
  const val = this.isVisible();
  this.focusDefaultDay();
});
```

### Pattern 3 — `@Input()` + `@Output()` pair → `model()`

```ts
// Before
@Input() value: boolean;
@Output() valueChange = new EventEmitter<boolean>();

// After
readonly value = model(false);

// Writing back from inside the component
this.value.set(false); // automatically emits valueChange
```

### Pattern 4 — `@ViewChildren` → `viewChildren()`

```ts
// Before
@ViewChildren('ref') items: QueryList<ElementRef>;

ngAfterViewInit(): void {
  this.items.changes.subscribe(list => this.helper.items = list);
}

// After
readonly items = viewChildren<ElementRef>('ref');

private readonly itemsEffect = effect(() => {
  this.helper.items = this.items();
});
```

### Pattern 5 — Multiple trigger signals with a guarded re-sanitization

A common case in components with several "visibility" or "feature flag"
signals: you need to re-run some sanitization logic whenever **any** of
several signals change, but the logic also reads and conditionally rewrites
a `model()` value. Track only the trigger signals, read the model value with
`untracked()`, and guard the write with an equality check to avoid loops:

```ts
readonly showLine1 = input(true);
readonly showLine2 = input(true);
readonly value = model<Address>();

private readonly sanitizeEffect = effect(() => {
  // tracked dependencies
  const showLine1 = this.showLine1();
  const showLine2 = this.showLine2();

  // read without subscribing to `value` itself
  const current = untracked(() => this.value());
  if (!current) return;

  const sanitized: Address = { ...current };
  if (!showLine1) sanitized.addressLine1 = null;
  if (!showLine2) sanitized.addressLine2 = null;

  if (!this.addressesEqual(sanitized, current)) {
    this.value.set(sanitized);
  }
});
```

---

## Inheritance caveat

Signal inputs are **not inherited**. Angular registers them at compile time
via the `@Component` decorator — TypeScript inheritance alone is not enough.

```ts
export class BaseComponent {
    readonly isVisible = input<boolean>(false); // ❌ not seen by child's Angular metadata
}

export class ChildComponent extends BaseComponent {
    // isVisible is not recognized as an Angular input here
}
```

### Solutions

**Override in the child** — verbose but explicit:

```ts
export class ChildComponent extends BaseComponent {
    override readonly isVisible = input<boolean>(false);
}
```

**Prefer composition over inheritance:**

```ts
export class ChildComponent {
    readonly isVisible = input<boolean>(false);
    // shared behavior via inject() or a shared service
}
```

> ⚠️ This is why the Angular automatic migration tool is conservative around
> classes that are extended. Always audit your inheritance chain before migrating.

---

## Testing signals

### Setting inputs in tests

Use `fixture.componentRef.setInput()` for both `input()` and `model()`:

```ts
fixture.componentRef.setInput('minDate', [2020, 7, 15]);
fixture.componentRef.setInput('isVisible', true);
```

### Writing to a `model()` from a test

```ts
component.isVisible.set(true);
fixture.detectChanges();
```

### Reading a signal value in an expectation

```ts
// 🔴 Wrong — reads the signal object, not the value
expect(component.isVisible).toBeTrue();

// 🟢 Correct — call the signal to read its value
expect(component.isVisible()).toBeTrue();
```

### Effects and timing

Effects are asynchronous relative to `detectChanges()`.
Always use `await fixture.whenStable()` after triggering a signal change
that runs an effect:

```ts
component.isVisible.set(true);
await fixture.whenStable();
fixture.detectChanges();
```

When testing behavior triggered by `model()` changes (e.g. focus management),
reproduce the real toggle rather than calling internal methods directly:

```ts
// 🔴 Fragile — bypasses the effect
component.focusDefaultDay();

// 🟢 Robust — triggers the full reactive chain
component.isVisible.set(false);
await fixture.whenStable();
component.isVisible.set(true);
await fixture.whenStable();
fixture.detectChanges();
```

### Testing `untracked()` reads

`untracked()` is invisible to the test from the outside — there's nothing
to assert about it directly. What you _can_ and should assert is the
**dependency boundary** it creates: changing the untracked signal alone
should not cause the effect to re-run.

```ts
// component reads `this.config` via untracked() inside an effect
// that is otherwise only triggered by `this.userId`

component.config.set({ theme: 'dark' }); // untracked — should NOT trigger the effect
await fixture.whenStable();
expect(loggerSpy).not.toHaveBeenCalled();

component.userId.set('123'); // tracked — SHOULD trigger the effect
await fixture.whenStable();
expect(loggerSpy).toHaveBeenCalledWith('123', { theme: 'dark' });
```

---

## Common pitfalls

### 1. Using `model()` where `input()` is enough

`model()` implies two-way binding. If the child never writes back,
use `input()` — it is simpler and communicates intent clearly.

### 2. Using `computed()` where `model()` is needed

If the parent and child both need to write a value, `computed()` is read-only
and will not work. Use `model()`.

### 3. Calling `.set()` inside `computed()`

```ts
// 🔴 Runtime error
readonly x = computed(() => {
  this.y.set(this.z() + 1); // forbidden
  return this.z();
});
```

### 4. Forgetting to call signals in templates

```html
<!-- 🔴 Renders the signal object -->
{{ mySignal }}

<!-- 🟢 Renders the value -->
{{ mySignal() }}
```

### 5. Spreading a `viewChildren()` signal without guarding

```ts
// 🔴 TypeError if the signal returns undefined during init
const items = [...this.daysButtons()];

// 🟢 Safe
const items = [...(this.daysButtons() ?? [])];
```

### 6. Over-tracking inside `effect()` — forgetting `untracked()`

An `effect()` tracks **every** signal it reads, not just the ones you
intended as triggers. Reading a signal "just to get its current value"
inside an effect still subscribes the effect to it, which can cause:

- redundant re-runs when an unrelated signal changes, or
- infinite loops when the effect reads and then (directly or indirectly)
  writes to the same signal

```ts
// 🔴 `this.value()` is tracked, even though the intent was just to read
// the current value before writing a sanitized version of it
effect(() => {
    const sanitized = this.sanitize(this.value());
    this.value.set(sanitized); // may re-trigger this same effect
});

// 🟢 Read without tracking; only intentional triggers remain tracked
effect(() => {
    const current = untracked(() => this.value());
    const sanitized = this.sanitize(current);
    if (sanitized !== current) {
        this.value.set(sanitized);
    }
});
```

### 7. Using `untracked()` instead of an equality check

`untracked()` controls what _triggers_ an effect — it does not make a write
inside the effect "safe" by itself. If the effect's only tracked dependencies
are, say, two visibility flags, and the write always replaces `value` with a
new object (even when nothing actually changed), the effect can still cause
unnecessary downstream updates (re-renders, parent `valueChange` emissions,
form dirty-state changes). Pair `untracked()` with an explicit equality
check before writing:

```ts
// 🔴 Always writes a new object, even when sanitization changed nothing
effect(() => {
    this.showLine1();
    const current = untracked(() => this.value());
    this.value.set({ ...current }); // new reference every time, even if no-op
});

// 🟢 Only writes when the sanitized result actually differs
effect(() => {
    this.showLine1();
    const current = untracked(() => this.value());
    const sanitized = this.sanitize(current);
    if (!this.isEqual(sanitized, current)) {
        this.value.set(sanitized);
    }
});
```

### 8. Mutating a signal's value instead of reassigning

This is the signals-era version of "mutating `@Input()` used to work."
Pre-signals, Zone.js-driven change detection re-read template expressions
on virtually every async event, so mutating a nested property or an array
in place and letting CD "catch it eventually" appeared to work. Signals
only notify subscribers on `.set()`/`.update()` — any in-place mutation of
the value returned by `signal()`/`model()`/`input()` is invisible to the
signal, the template, and any `effect()`/`computed()` depending on it,
because the object/array reference never changes and signals compare by
reference by default.

The fix is always the same shape: read the current value, produce a
**new top-level reference** with the change applied, and pass that to
`.set()` or `.update()`. Never call a mutating method or assign a nested
property directly on `signalOrModel()`.

#### 8a. Nested object property

```ts
// 🔴 Silent no-op from the signal's perspective
this.address().locality.name = 'newName';

// 🟢 New top-level reference — the signal and bound parent both update
this.address.update((current) => ({
    ...current,
    locality: { ...current.locality, name: 'newName' },
}));
```

#### 8b. Two-way binding directly on an array element inside `@for`

Binding `[(model)]` straight to an indexed read of a signal
(`model()[i]`) is a variant of the same mistake: the "write" side of the
banana-in-a-box syntax tries to assign into `model()[i]`, which mutates
the array in place instead of going through `.set()`/`.update()`, so
nothing propagates and Angular may also warn about an unsupported
two-way expression.

```html
<!-- 🔴 Tries to write through model()[i] — mutates in place, breaks reactivity -->
@for (item of model(); track item.id; let i = $index) {
<app-address-row [(model)]="model()[i]" />
}

<!-- 🟢 One-way in, explicit handler out -->
@for (item of model(); track item.id; let i = $index) {
<app-address-row [model]="model()[i]" (modelChange)="updateItem(i, $event)" />
}
```

```ts
updateItem(index: number, newValue: NomAdresse): void {
    this.model.update((current) =>
        current.map((item, i) => (i === index ? newValue : item)),
    );
}
```

#### 8c. Array mutating methods (`push`, `splice`, `pop`, `shift`, `unshift`, `sort`, `reverse`)

All of these mutate the array in place and return either the mutated
array, the removed element(s), or nothing — never a new reference. Since
they operate on `this.model()` (the _value_, not the signal), Angular has
no way to know the array changed.

```ts
// 🔴 Adds an item, but the signal reference is untouched — no re-render
this.model().push({ name: null, address: null });

// 🟢 New array reference via spread
this.model.update((current) => [...current, { name: null, address: null }]);
```

```ts
// 🔴 Removes an item in place — invisible to the signal
this.model().splice(index, 1);

// 🟢 filter() naturally returns a new array
this.model.update((current) => current.filter((_, i) => i !== index));
```

```ts
// 🔴 Same problem with pop() / shift() / unshift()
this.model().pop();
this.model().shift();
this.model().unshift(newItem);

// 🟢 Equivalent immutable forms
this.model.update((current) => current.slice(0, -1)); // pop
this.model.update((current) => current.slice(1)); // shift
this.model.update((current) => [newItem, ...current]); // unshift
```

```ts
// 🔴 sort() / reverse() mutate AND return the same array reference —
// even risky to combine with spread if you forget it: [...current].sort()
// mutates the *new* array in place, which is fine, but sorting
// `this.model()` directly still mutates the one held by the signal
this.model().sort((a, b) => a.name.localeCompare(b.name));

// 🟢 Copy first, then sort/reverse the copy
this.model.update((current) =>
    [...current].sort((a, b) => a.name.localeCompare(b.name)),
);
```

#### 8d. Direct index assignment

```ts
// 🔴 Mutates the array element in place
this.model()[index] = newValue;

// 🟢 map() to swap out just that index
this.model.update((current) =>
    current.map((item, i) => (i === index ? newValue : item)),
);
```

#### 8e. `Object.assign()` on the current value

`Object.assign(target, ...)` mutates and returns `target`. Passing
`this.model()` as the target mutates the value in place, even though the
call "looks" like it's producing something.

```ts
// 🔴 target is this.model() itself — mutated in place
Object.assign(this.model(), { name: 'newName' });

// 🟢 target is a fresh object — this is what Object.assign() is for
this.model.update((current) => Object.assign({}, current, { name: 'newName' }));
// or, more idiomatically:
this.model.update((current) => ({ ...current, name: 'newName' }));
```

#### 8f. `Map` / `Set` values

`Map` and `Set` are reference types too, and their mutating methods
(`.set()` on a `Map`, `.add()`/`.delete()` on a `Set`) don't return a new
`Map`/`Set` — they mutate and return `this`, which is easy to miss since
`Map.prototype.set` shares a name with `WritableSignal.set`.

```ts
// 🔴 This is Map.prototype.set, not the signal's — mutates the same Map instance
this.cache().set(key, value);

// 🟢 Build a new Map from the old one
this.cache.update((current) => new Map(current).set(key, value));
```

```ts
// 🔴 Set.prototype.delete mutates in place
this.selectedIds().delete(id);

// 🟢 Copy into a new Set, then mutate the copy
this.selectedIds.update((current) => {
    const next = new Set(current);
    next.delete(id);
    return next;
});
```

> 💡 General rule of thumb: if a method's name suggests it changes
> something "in place" and doesn't hand you back a brand-new
> object/array/Map/Set, assume it mutates and wrap it in a copy first.
> When unsure, check the return type — a genuinely immutable operation
> (`map`, `filter`, `concat`, `slice`, spread) always returns a fresh
> reference you can pass straight to `.set()`/`.update()`.
