Sub topic 7
Reading nested state with deep signals
This chapter assumes you know withState, patchState and withComputed from the earlier chapters. It also assumes you know the Angular signal and computed functions. You will learn how a store exposes nested objects as signals you can read at any depth. You will also learn where that stops working and how to update nested values correctly.
The problem deep signals solve
withState turns each top-level property of your state into a signal. A state with user and ui properties gives you store.user and store.ui. Calling store.user() returns the whole user object.
Real state is often nested. If a component only needs the user's city, reading store.user().address.city has two drawbacks:
- You write a long chain of property access after the call.
- A
computedthat readsstore.user()becomes dirty whenever any part ofuserchanges, even whencitydid not.
A deep signal is a signal that also carries child signals for each property of a nested object. You can write store.user.address.city() and get a signal that only changes when the city changes.
Reading nested properties
The store below has two nested objects and one array.
import { computed } from '@angular/core';
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals';
type Theme = 'light' | 'dark';
type SettingsState = {
user: {
name: string;
address: { city: string; country: string };
};
ui: { theme: Theme; sidebarOpen: boolean };
tags: string[];
};
const initialState: SettingsState = {
user: { name: 'Ada', address: { city: 'London', country: 'UK' } },
ui: { theme: 'light', sidebarOpen: true },
tags: ['admin'],
};
export const SettingsStore = signalStore(
{ providedIn: 'root' },
withState(initialState),
withComputed(({ user, ui }) => ({
greeting: computed(() => `Hello ${user.name()} from ${user.address.city()}`),
isDark: computed(() => ui.theme() === 'dark'),
})),
withMethods((store) => ({
moveTo(city: string, country: string): void {
patchState(store, (state) => ({
user: { ...state.user, address: { city, country } },
}));
},
toggleSidebar(): void {
patchState(store, (state) => ({
ui: { ...state.ui, sidebarOpen: !state.ui.sidebarOpen },
}));
},
setTheme(theme: Theme): void {
patchState(store, (state) => ({ ui: { ...state.ui, theme } }));
},
})),
);The state signals passed to withComputed are deep signals too. That is why user.address.city() works inside the greeting computed.
In a component, the store exposes the same shape:
import { Component, inject } from '@angular/core';
import { SettingsStore } from './settings.store';
@Component({
selector: 'app-profile',
template: `
<h2>{{ store.user.name() }}</h2>
<p>{{ store.user.address.city() }}, {{ store.user.address.country() }}</p>
<button (click)="store.setTheme(store.isDark() ? 'light' : 'dark')">
Theme: {{ store.ui.theme() }}
</button>
<button (click)="store.moveTo('Paris', 'France')">Move to Paris</button>
`,
})
export class ProfileComponent {
readonly store = inject(SettingsStore);
}Each of store.user.name, store.user.address.city and store.ui.theme is a Signal. You can pass any of them to computed, effect or toObservable, or call them in a template.
How it works internally
A deep signal is the parent signal with extra properties added on top of it. The library does not create a signal for every nested property up front. When you first access store.user.address, it creates a computed that reads the parent value and picks the address property. It then caches that computed. Nested objects get the same treatment recursively.
Two consequences follow:
- Unused branches of the state cost nothing, because their signals are never created.
- The same property read twice returns the same signal instance, so reads are cheap and stable.
The diagram shows how the signals relate.
Fine-grained change notification
Each child is a computed signal, so it uses the normal signal equality check. After moveTo('London', 'France') runs on the store above:
store.user()returns a new object, becausepatchStatereplaced it.store.user.address()returns a new object.store.user.address.country()returns a new value.store.user.address.city()still returns'London'. Its value is equal to the old one, so anything that depends only on the city is not notified.store.user.name()is unchanged for the same reason.
This is the practical benefit. A computed that depends on user.address.city() does not rerun when the country changes. A computed that depends on user() does.
Which values become deep signals
Only plain objects get child signals. Everything else stays an ordinary Signal.
| Value type in state | What you get | Example access |
|---|---|---|
| Plain object | `DeepSignal` with child signals | `store.user.name()` |
| Array | Plain `Signal` | `store.tags()` |
| Primitive (string, number, boolean) | Plain `Signal` | `store.ui.theme()` |
| `Date`, `Map`, `Set`, class instance | Plain `Signal` | `store.createdAt()` |
| Object type that may be `null` or `undefined` | Plain `Signal` | `store.profile()` |
The last row matters in practice. The types decide this, not only the runtime value. If you declare profile: Profile | null, TypeScript cannot know the object exists, so store.profile is a plain signal. You read it with store.profile()?.name. If you want deep access, model the state so the object is always present and store a flag or default values instead.
type Profile = { name: string; bio: string };
type WithOptional = { profile: Profile | null }; // store.profile is Signal<Profile | null>
type WithDefaults = { profile: Profile }; // store.profile.name is Signal<string>Arrays need another approach. You cannot write store.tags[0](). Read the array and index into it inside a computed:
const firstTag = computed(() => store.tags()[0] ?? null);If the items are records you look up by id, use withEntities, which a later chapter covers.
Updating nested state
Reading is deep, but updating is not. patchState merges its argument into the state at the top level only. If you pass { user: { address: { city: 'Paris' } } }, the whole user property is replaced, and name and country are lost.
To change one nested value, copy each object along the path to it and replace only the leaf:
patchState(store, (state) => ({
user: {
...state.user,
address: { ...state.user.address, city: 'Paris' },
},
}));The spread operator copies the unchanged siblings. This gives you new objects along the changed path and keeps the same object references everywhere else. Unchanged branches keep their identity, so signals that read them stay quiet.
The deeper the nesting, the more verbose this gets. You can keep it manageable in two ways:
- Write small updater functions that return a partial state, such as
setCity(city), and pass their result topatchState. The custom features chapter shows this pattern. - Flatten the state when the nesting does not carry meaning. State shaped for the screen is easier to update than state that mirrors a server response.
Common errors
- Calling the signal too early.
store.user().nameworks, butstore.user.nameis a function, not a string. In a template,{{ store.user.name }}prints the function source. Writestore.user.name(). - Expecting deep signals on arrays or nullable objects. If TypeScript reports that a property does not exist on
Signal<...>, check the type in the table above. Fix the state type, or read the value with()and use optional chaining. - Replacing a branch with a partial object. Passing only the changed property to
patchStatedrops the siblings. Always spread the existing object. - Depending on the parent when you need the leaf. A
computedthat readsstore.user()reruns for every user change. Readstore.user.address.city()when the city is all you use. - Putting changing keys in state. The set of top-level keys is fixed when
withStateruns. Child signals for nested objects are created from the current value, so a record with dynamic keys is better stored as an entity collection or as aRecordtype read inside a computed.
When to use deep signals
Use them when a component or computed needs one field of a stable nested object, such as settings, form drafts, or filters grouped under a filter property. They add no setup and no cost for what you do not read.
Skip them when the data is a list or a lookup table. A list belongs in an array or an entity collection. A value that can be absent belongs in a type that makes the absence explicit. In both cases you read the top-level signal and derive what you need with computed.
Exercise
A store has the state { cart: { items: CartItem[]; coupon: string | null; totals: { net: number; tax: number } } }. Which of these reads work as signals? (a) store.cart.totals.tax (b) store.cart.items[0] (c) store.cart.coupon.length. For each one that does not, say how to read the value instead.
Show answer
(a) works. cart and totals are plain objects, so store.cart.totals.tax is a Signal<number> and you call it with (). (b) does not work. items is an array, so store.cart.items is a plain Signal<CartItem[]>. Read it with computed(() => store.cart.items()[0]). (c) does not work. coupon is string | null, so store.cart.coupon is a plain Signal<string | null>, and the string has no child signals. Read it with computed(() => store.cart.coupon()?.length ?? 0).
Exercise
Write the patchState call that changes only store.user.address.country to 'France' in the SettingsStore from this chapter. Then say which of store.user.name() and store.user.address.city() notify their dependents after the call.
Show answer
patchState(store, (state) => ({ user: { ...state.user, address: { ...state.user.address, country: 'France' } } }));. Neither store.user.name() nor store.user.address.city() notifies its dependents. Both values are equal to the previous ones, and each child signal compares its value with the last one, so only readers of store.user(), store.user.address() and store.user.address.country() are notified.