Signals and Angular Reactivity
Why this matters
Section titled “Why this matters”Signals are not a new syntax for the same thing. They change who is responsible for knowing that state changed — moving it from a global mechanism that guesses (ZoneJS) to the value itself, which knows exactly who read it.
That shift is why signals are the foundation of zoneless Angular, why OnPush could become the default, and why so much Angular guidance written before them is now actively misleading. Getting the model right is the difference between a codebase that gets simpler as it grows and one that accumulates a web of effects nobody can reason about.
Terminology
Section titled “Terminology”- Signal — a wrapper around a value that notifies interested consumers when the value changes. You read it by calling it:
count(). - Writable signal (
WritableSignal<T>) — created withsignal(), updated with.set()or.update(). - Computed signal (
Signal<T>) — read-only, derived from other signals viacomputed(). - Producer / consumer — the signal being read is the producer; the code reading it is the consumer.
- Reactive context — a runtime state in which Angular monitors signal reads and records dependencies.
- Tracking — the act of recording that a consumer depends on a producer.
- Glitch-free — the guarantee that consumers never observe a partially-updated derivation.
The mental model
Section titled “The mental model”A signal graph is a pull-based dependency graph with push-based invalidation.
- Push: writing a signal does not recompute anything. It marks its dependents stale and propagates that marking through the graph.
- Pull: a value is only recomputed when someone reads it and finds it stale.
Two consequences follow directly, and they explain most signal behaviour:
- A
computednobody reads costs nothing. No reader, no recomputation — ever. - Dependencies are recorded per execution, not declared. Whatever signals were actually read during the last run are the dependency set. Take a different branch, get a different set.
Compare that with RxJS, which is push-based end to end: values flow whether or not anyone needs them, in whatever order the operators impose. Signals give you consistency by construction; observables give you control over time. This is why the two coexist rather than one replacing the other.
The minimal example
Section titled “The minimal example”import { signal, computed } from '@angular/core';
const count = signal(0);const doubled = computed(() => count() * 2);
count(); // 0doubled(); // 0
count.set(3);doubled(); // 6 — recomputed on this read, not on the set
count.update((n) => n + 1);count(); // 4Three details in four lines that matter later:
count()is a getter call, not a property. That is what lets Angular observe the read.computeddid not run atcount.set(3). It ran at the nextdoubled()read..update()receives the previous value. Prefer it overset(count() + 1), which reads the signal — and inside a reactive context, that read creates a dependency you probably did not want.
Writable signals in practice
Section titled “Writable signals in practice”Equality controls everything
Section titled “Equality controls everything”Signals compare with Object.is by default. A write producing an equal value notifies nothing — that is a feature, and it is also the single most common source of “my signal isn’t updating”:
const orders = signal<Order[]>([]);
// Does nothing. Same array reference.orders().push(newOrder);orders.set(orders());
// Correct. New reference.orders.update((current) => [...current, newOrder]);Treat signal values as immutable. If you need value-based comparison instead, supply an equal function:
import isEqual from 'lodash/isEqual';
const filters = signal({ status: 'pending' }, { equal: isEqual });filters.set({ status: 'pending' }); // no notification — deeply equalCustom equality works on both writable and computed signals. Weigh it carefully: a deep comparison runs on every write, and on large objects that can cost more than the render you avoided.
Expose read-only, keep writes private
Section titled “Expose read-only, keep writes private”WritableSignal has an asReadonly() method. Use it at every service boundary:
import { Service, computed, signal } from '@angular/core';
@Service()export class CartState { private readonly _items = signal<readonly CartItem[]>([]); readonly items = this._items.asReadonly();
readonly total = computed(() => this._items().reduce((sum, i) => sum + i.price * i.quantity, 0), );
add(item: CartItem): void { this._items.update((items) => [...items, item]); }
clear(): void { this._items.set([]); }}@Service() is the modern shorthand for @Injectable({ providedIn: 'root' }); either works, and @Injectable is still required for constructor injection or useClass/useValue/useExisting/useFactory providers.
Consumers can read items() and total() but cannot write. This is the signal-era equivalent of exposing a Subject as an Observable — and it is just as important, because a public WritableSignal invites any component to mutate shared state from anywhere.
One caveat the official docs are explicit about: asReadonly() does not prevent deep mutation of the value. It stops set and update; it does not freeze the object. Type the value as readonly/Readonly<T> so the compiler helps.
Computed signals
Section titled “Computed signals”Lazy and memoised
Section titled “Lazy and memoised”computed does not run until first read, caches the result, and invalidates the cache when a dependency changes. That combination means expensive derivations — filtering, sorting, aggregating — are safe to put in a computed even when the template reads them several times.
readonly visibleOrders = computed(() => { const term = this.filter().toLowerCase(); return this.orders().filter((o) => o.customer.toLowerCase().includes(term));});Three template reads of visibleOrders() produce one filter pass. Three template calls of a filterOrders() method produce three, on every check of that view. That is the practical argument for computed over template methods.
Dependencies are dynamic
Section titled “Dependencies are dynamic”Only signals actually read during a run are tracked:
const showCount = signal(false);const count = signal(0);
const label = computed(() => showCount() ? `The count is ${count()}.` : 'Nothing to see here!',);While showCount() is false, count is not a dependency — updating it does not invalidate label. Flip showCount to true and the next read takes the other branch, adding count to the dependency set. Dependencies can be removed as well as added.
This is usually exactly what you want. It becomes a trap when a derivation short-circuits: computed(() => this.hasAccess() && this.expensive()) will silently stop tracking expensive whenever hasAccess() is false.
Computed signals are not writable
Section titled “Computed signals are not writable”doubled.set(3) is a compile error. When you need a value that is both derived and directly settable, that is linkedSignal — see below. Reaching for an effect to copy one signal into another is the wrong answer, and it is the most common signal anti-pattern in the wild.
Reactive contexts
Section titled “Reactive contexts”Angular enters a reactive context — and therefore tracks reads — when:
- Executing an
effectorafterRenderEffectcallback. - Evaluating a
computed. - Evaluating a
linkedSignal. - Evaluating a
resource’sparamsor loader function. - Rendering a component template, including host property bindings.
Anywhere else — an event handler, a service method, a lifecycle hook — reading a signal is just reading a value. No dependency is created.
The async boundary
Section titled “The async boundary”This is the rule people learn the hard way: the reactive context is only active for synchronous code. Signal reads after an await are not tracked.
// Broken: theme() is read after the await, so it is never a dependency.effect(async () => { const data = await fetchUserData(); console.log(`User: ${data.name}, Theme: ${theme()}`);});
// Correct: read before the await.effect(async () => { const currentTheme = theme(); const data = await fetchUserData(); console.log(`User: ${data.name}, Theme: ${currentTheme}`);});Passing a signal read as an argument also works, because arguments evaluate synchronously: await renderContent(docContent()).
The failure mode is silent. The effect runs once, appears to work, and simply never re-runs. Read every signal you depend on at the top of the callback, before any await.
Reading without tracking
Section titled “Reading without tracking”untracked reads a signal without creating a dependency:
effect(() => { // Re-runs when currentUser changes; ignores counter changes. console.log(`User ${currentUser()}, counter ${untracked(counter)}`);});It also takes a callback, which is the form to use when calling out to code that might read signals you do not want to depend on:
effect(() => { const user = currentUser(); untracked(() => this.analytics.track('user-changed', user));});Without that wrapper, any signal the analytics service happens to read silently becomes a dependency of your effect — a genuinely difficult bug to find later.
Guarding against accidental contexts
Section titled “Guarding against accidental contexts”assertNotInReactiveContext throws if code that must not be tracked is running inside one. Pass the calling function so the error names the right API:
import { assertNotInReactiveContext } from '@angular/core';
function subscribeToEvents(): Subscription { assertNotInReactiveContext(subscribeToEvents); // ...}Useful in library code and in anything that starts subscriptions or long-lived work, where being re-executed by a tracking consumer would leak.
Effects
Section titled “Effects”An effect runs whenever one or more signals it reads change. It runs at least once, always asynchronously, during change detection.
effect(() => { localStorage.setItem('orders-filter', this.filter());});Effects should be your last resort
Section titled “Effects should be your last resort”The official guidance is unusually direct: “There are no situations where effect is good, only situations where it is appropriate.” Prefer computed for derived values and linkedSignal for values that are both derived and settable. If you are copying one signal into another with an effect, move the source of truth higher and use computed instead.
Effects are for syncing signal state to imperative, non-signal APIs:
- Logging and analytics.
- Persisting to
localStorage, session storage, cookies. - Custom DOM behaviour that templates cannot express.
- Driving a
<canvas>, a charting library, or another third-party UI library.
Angular explicitly warns against using effects to propagate state changes: it causes ExpressionChangedAfterItHasBeenChecked errors, infinite circular updates, and unnecessary change-detection cycles.
Injection context and lifetime
Section titled “Injection context and lifetime”effect() must be created in an injection context — typically a constructor or a field initialiser. Outside one, pass an injector:
private readonly injector = inject(Injector);
startLogging(): void { effect(() => console.log(this.count()), { injector: this.injector });}Effects come in two flavours with different timing and lifetime:
| Created in | Runs | Destroyed | |
|---|---|---|---|
| View effect | Component instantiation (including services bound to component injectors) | Before its component is checked | With the component |
| Root effect | A root-provided service | Before all components are checked | With the application |
If an effect’s dependencies change during its own execution, it re-runs before change detection continues.
Effects return an EffectRef with a destroy() method. Combine it with the manualCleanup option to opt out of automatic teardown — and then genuinely destroy it, or you have a leak.
Cleanup functions
Section titled “Cleanup functions”The effect callback receives an onCleanup registrar, invoked before the next run and on destruction:
effect((onCleanup) => { const controller = new AbortController(); fetch(`/api/orders/${this.orderId()}`, { signal: controller.signal }) .then((r) => r.json()) .then((data) => this.details.set(data));
onCleanup(() => controller.abort());});Without the cleanup, rapid changes to orderId() produce overlapping requests that can resolve out of order and write a stale result last. (In practice, resource handles this case for you — see below.)
afterRenderEffect for DOM work
Section titled “afterRenderEffect for DOM work”effect runs before Angular updates the DOM. When you need to touch the committed DOM — measuring, or driving a third-party widget — use afterRenderEffect:
@Component({ /* ... */ })export class RevenueChart { readonly chartData = input.required<ChartData>(); private readonly canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('canvas'); private chart!: ChartInstance;
constructor() { afterNextRender({ write: () => { this.chart = initializeChart(this.canvas().nativeElement, this.chartData()); }, });
afterRenderEffect(() => this.chart.updateData(this.chartData())); }}afterRenderEffect supports four phases — earlyRead, write, mixedReadWrite, read — executed in that order, so all reads can be batched away from all writes and avoid layout thrashing. Each phase receives the previous phase’s return value as a signal.
If you do not specify a phase, callbacks run in mixedReadWrite, which can worsen performance by causing extra reflows. Always name the phase you actually need.
afterRenderEffect and its siblings only run on the client, never during server-side rendering, and components are not guaranteed to be hydrated when the callback runs. And before reaching for it at all: ResizeObserver, MutationObserver and IntersectionObserver are usually the better tool for reacting to DOM changes.
linkedSignal: derived and writable
Section titled “linkedSignal: derived and writable”The classic problem: a selection that derives from a list but can also be set by the user.
// Broken: never updates when shippingOptions changes.selectedOption = signal(this.shippingOptions()[0]);If shippingOptions changes, selectedOption may now hold something that is not a valid option. linkedSignal takes a computation instead of an initial value, so it re-derives when its source changes but stays writable in between:
selectedOption = linkedSignal(() => this.shippingOptions()[0]);The two-argument form lets the computation see the previous value, so you can preserve a user’s choice when it is still valid:
selectedOption = linkedSignal<ShippingMethod[], ShippingMethod>({ source: this.shippingOptions, computation: (newOptions, previous) => newOptions.find((opt) => opt.id === previous?.value.id) ?? newOptions[0],});This pattern — “reset when the source changes, but keep the selection if it survives” — is extremely common (a selected row in a refreshed table, a chosen tab, a highlighted item). Before linkedSignal it was invariably written as an effect that wrote to a signal, which is exactly the anti-pattern the framework now warns against.
Async state: resource
Section titled “Async state: resource”All core signal APIs are synchronous. resource bridges async data into the signal world, exposing status and value as signals.
const orderResource = resource({ params: () => ({ id: this.orderId() }), loader: ({ params, abortSignal }) => fetch(`/api/orders/${params.id}`, { signal: abortSignal }).then((r) => r.json()),});paramsis a reactive computation. When signals it reads change, a new params value is produced and the loader re-runs.- If
paramsreturnsundefined, the loader does not run and the status becomes'idle'. This is the idiomatic way to express “not ready yet.” - The loader receives
abortSignal, and Angular aborts an in-flight load whenparamschanges. Passing it tofetchgives you correct cancellation for free — the manualAbortControllerdance from the effect example above, handled. reload()re-runs the loader on demand.
Status
Section titled “Status”| Status | value() |
Meaning |
|---|---|---|
'idle' |
undefined |
No valid request; loader has not run |
'loading' |
undefined |
Loading because params changed |
'reloading' |
previous value | Loading because reload() was called |
'resolved' |
resolved value | Loader completed |
'error' |
undefined |
Loader threw |
'local' |
locally set value | Value set via .set() / .update() |
The distinction between 'loading' and 'reloading' is the useful one for UI: 'loading' should show a skeleton (there is no value), 'reloading' should keep the current data visible with a subtle indicator (there is one).
Use hasValue() rather than checking value() against undefined — it acts as a type guard and protects against reading value() in an error state, which throws.
Streaming, chaining and HTTP
Section titled “Streaming, chaining and HTTP”streaminstead ofloaderfor sources that emit repeatedly — WebSockets, server-sent events, snapshot listeners.chainin theparamscontext expresses a dependency between resources while propagating status correctly: if the upstream is loading, the downstream is loading; if it errored, the downstream errored. Readingupstream.value()directly inparams“works” but collapses every upstream state into'idle'. Pass the chained value directly rather than wrapping it in an object —{ companyId: undefined }is still a defined params value, so the loader would run with an undefined id.httpResourcewrapsHttpClient, so requests go through the normal Angular HTTP stack including interceptors. Prefer it over rawfetchin an application that has interceptors for auth, tracing or error handling.rxResourcefrom@angular/core/rxjs-interoptakes astreamfactory returning an Observable, for services that already expose observables.
SSR caching, and a real security consideration
Section titled “SSR caching, and a real security consideration”Giving a resource an id stores its resolved value in TransferState on the server so the client does not re-fetch during hydration:
const productResource = resource({ params: () => ({ id: this.productId() }), loader: ({ params }) => fetchProduct(params), id: 'product-detail',});The id must be unique in the application and identical on server and client.
The cached value is serialised into the page’s HTML. Do not set id on a resource that loads data specific to the user who triggered the render — especially where the rendered HTML might be cached by a CDN or shared between users. That is a data-leak vector, not just a correctness concern. Use id for shared, cacheable data; leave it off for anything per-user.
RxJS interop
Section titled “RxJS interop”Signals and RxJS are not competitors. Signals model state; observables model events over time. Convert at the boundary.
toSignal
Section titled “toSignal”readonly user = toSignal(this.userService.currentUser$, { initialValue: null });- Subscribes immediately — which may trigger side effects — and unsubscribes automatically when the creating context is destroyed.
- Needs an injection context, or an explicit
injector. - Observables may not emit synchronously, but signals always need a value. Choose one of:
initialValue, acceptundefineduntil the first emission, orrequireSync: truewhen the source is guaranteed synchronous (aBehaviorSubject, say) — which also removesundefinedfrom the type. - If the source errors, the error is thrown when the signal is read. If it completes, the signal keeps returning the last emitted value.
manualCleanupopts out of automatic teardown, for observables that complete naturally.- Do not call
toSignalrepeatedly for the same observable — each call is a new subscription. Create it once and reuse.
toObservable
Section titled “toObservable”readonly query$ = toObservable(this.query);readonly results$ = this.query$.pipe( debounceTime(300), distinctUntilChanged(), switchMap((q) => this.http.get<Result[]>(`/api/search?q=${q}`)),);Timing matters here. toObservable tracks the signal with an effect writing into a ReplaySubject. The first value may be emitted synchronously on subscription; everything after is asynchronous. And because signals never notify synchronously, three rapid set calls emit once, with the final value:
mySignal.set(1);mySignal.set(2);mySignal.set(3);// the subscriber sees 3That coalescing is a feature for rendering and a hazard if you were relying on an observable to see every intermediate state. If you need every value, the source of truth should be a Subject, not a signal.
Choosing
Section titled “Choosing”| Need | Use |
|---|---|
| Current value of application state | signal |
| Value derived from other state | computed |
| Derived but user-overridable | linkedSignal |
| Async data with loading/error states | resource / httpResource |
Debouncing, retry, switchMap, complex timing |
RxJS, then toSignal at the boundary |
| A stream of discrete events (not state) | RxJS Subject |
The pragmatic rule: RxJS in the middle, signals at the edges. Do the time-based orchestration with operators; hand a signal to the template.
Under the hood
Section titled “Under the hood”Producers and consumers with version counters. Each signal holds a version that increments on a value change. Each consumer records the producers it read and the versions it saw. Reading a stale computed compares recorded versions against current ones; if none actually changed, the cached value is returned without re-running the derivation. This is why a write-then-write-back sequence that ends at the original value does not cause downstream recomputation.
Dynamic dependency tracking uses a global “current consumer”. Entering a reactive context sets a module-level pointer; calling a signal’s getter registers the edge from that pointer. That is precisely why an await breaks tracking — the pointer is restored when the synchronous portion returns, long before the continuation runs.
Signals mark whole views, not expressions. A template reading a signal registers the entire view as a consumer. Angular does not know which interpolation depended on it. Splitting a fast-changing signal into a small child component is therefore a real optimisation, because it shrinks the view being marked dirty.
Effects are scheduled, not immediate. Writing a signal queues its effects; they run during change detection. This is what gives you glitch-freedom — several writes in the same tick produce one effect run, at a point where the graph is consistent. It is also why a test that sets a signal and immediately asserts on an effect’s side effect fails: you have to let change detection run.
Anti-patterns
Section titled “Anti-patterns”An effect that writes to a signal. The canonical mistake. effect(() => this.filtered.set(filter(this.items()))) should be computed. It costs an extra change-detection pass, risks ExpressionChangedAfterItHasBeenChecked, and can loop.
Chained effects. Effect A writes signal X, whose effect writes signal Y, whose effect writes Z. Ordering becomes implicit, debugging becomes archaeology. Model the whole thing as derivations from one source of truth.
Mutating a signal’s value in place. orders().push(x) notifies nothing. Always produce a new reference.
Reading a signal inside update. count.update(() => count() + 1) reads the signal; inside a reactive context that creates an unintended dependency. Use the callback parameter: count.update((n) => n + 1).
Exposing WritableSignal from a service. Any component can now write shared state from anywhere. Expose asReadonly() and methods.
toSignal called in a template or a method. Every call subscribes. Create it once as a field.
effect for data fetching. Use resource, which handles cancellation, status, and race conditions. A hand-rolled effect fetch is a race condition waiting for a slow network.
Deep equal on large objects. A deep comparison on every write can cost more than the render it saves. Measure before adopting it.
Failure modes and diagnosis
Section titled “Failure modes and diagnosis”| Symptom | Cause | Check |
|---|---|---|
| Signal set, template unchanged | Value Object.is-equal to the previous one |
Was the object mutated rather than replaced? |
computed never recomputes |
Dependency not read on the last run (branch not taken) | Log the branch; check for short-circuits |
| Effect runs once, never again | Signal read after an await |
Move every read above the first await |
| Effect fires on unrelated changes | Incidental read inside the callback | Wrap it in untracked |
ExpressionChangedAfterItHasBeenChecked |
An effect writing state during change detection | Replace with computed / linkedSignal |
| Infinite loop / browser hang | Circular effect writes | Map who writes each signal; break the cycle |
| Stale data after navigation | resource params does not read the route signal |
Ensure params reads the changing input |
| Old response overwrites new | Manual fetch without cancellation | Use resource, or onCleanup + AbortController |
toSignal throws on read |
Source observable errored | Handle with catchError before toSignal |
| Memory grows over time | manualCleanup effect never destroyed, or repeated toSignal |
Audit manualCleanup and per-call subscriptions |
The most useful diagnostic habit: for every signal, be able to name every place that writes it. If that list is longer than two or three, the state is not modelled well, and the bugs you are seeing are a symptom rather than the problem.
Performance
Section titled “Performance”Derive, do not duplicate. Every computed is memoised and lazy. Every effect-maintained copy is eager work plus an invariant you must maintain by hand.
Keep derivations pure and cheap where possible. A computed runs on read-after-invalidation. Sorting 10,000 rows in a computed read by three templates is one sort — but it is still a sort on every relevant change. Consider narrowing what invalidates it.
Split components around change frequency. Because marking is per view, a template mixing a per-second ticker with a large static table re-renders the table. Extract the ticker.
Use equal deliberately. Custom equality can prevent whole cascades — an object rebuilt on every poll but semantically unchanged is a common case. Just do not pay for a deep comparison on a large structure to avoid a cheap render.
Let resource cancel for you. Abandoned in-flight requests still cost bandwidth, server capacity and battery. resource aborts on params change automatically.
Bound your collections. A signal holding an ever-growing array from a live feed makes every derivation over it progressively slower. Cap the retained window.
Testing signals
Section titled “Testing signals”Signals test well because they are plain functions with no framework dependency for reading:
it('totals the cart', () => { const state = TestBed.inject(CartState);
state.add({ id: 'a', price: 10, quantity: 2 }); state.add({ id: 'b', price: 5, quantity: 1 });
expect(state.total()).toBe(25);});No TestBed.createComponent, no fixture, no change detection — computed recalculates on read. Signal-based state services are among the easiest things in Angular to test, which is a good reason to put logic there rather than in components.
Effects are different: they are scheduled, so you must let change detection run before asserting:
it('persists the filter', async () => { const fixture = TestBed.createComponent(OrdersPortal); fixture.componentInstance.filter.set('acme');
await fixture.whenStable();
expect(localStorage.getItem('orders-filter')).toBe('acme');});Setting a signal and asserting synchronously on an effect’s side effect will fail — correctly. See the testing guide for the full picture.
Trade-offs
Section titled “Trade-offs”| Decision | Favours | Costs |
|---|---|---|
| Signals over RxJS for state | Simpler mental model, synchronous reads, no subscription management | No operators for time; a second paradigm alongside existing RxJS |
| RxJS over signals for events | Rich time-based operators, backpressure, cancellation | Subscription lifecycle, harder to read synchronously |
computed over effect |
Lazy, memoised, no ordering questions | Must be pure and synchronous |
linkedSignal over effect-writes-signal |
Declarative, correct on source change | One more API to learn |
resource over manual fetch |
Cancellation, status, race safety | Less control over the exact request lifecycle |
Custom equal |
Prevents cascades from semantically-equal values | Comparison cost on every write |
| Signals in a service | Testable, sharable, framework-independent | Needs deliberate read-only boundaries |
Senior interview scenarios
Section titled “Senior interview scenarios”“When would you choose an effect over a computed?”
Only when the destination is not a signal. Persisting to storage, logging, driving a canvas or a third-party widget, custom DOM behaviour templates cannot express. If the output is a value other Angular code reads, it should be a computed — or a linkedSignal if it must also be settable. Copying a signal into another signal with an effect is the anti-pattern the framework explicitly warns about, because it risks ExpressionChangedAfterItHasBeenChecked, extra change-detection cycles, and circular updates.
“An effect fetches data. It runs once and never again. Why?”
Almost certainly a signal read after an await. The reactive context is synchronous only, so the continuation after an await is not tracked and no dependency is registered. The fix is to read every dependency before the first await — or, better, to use resource, whose params computation is the tracked part and whose loader is free to be async.
“Explain glitch-freedom and why it matters.”
A computed recomputes on read after invalidation, not eagerly on write. So a consumer can never observe a state where one derivation has updated and another has not, even when both depend on the same source. In a push-based system you have to sequence updates carefully to avoid intermediate inconsistent states; here consistency is structural.
“Signals or RxJS for a typeahead search?”
Both, at their strengths. The input is signal state. Debouncing, distinct-until-changed and switch-mapping are time-based orchestration, which is RxJS’s job — or httpResource/rxResource with the experimental debounced helper if you want to stay entirely in signals. Either way, cancellation of the superseded request is the non-negotiable part: with RxJS that is switchMap, with resource it is the automatic abort on params change.
“A page’s memory grows steadily. Where do you look in signal code?”
Effects created with manualCleanup that nothing ever destroys. toSignal called per render rather than once, creating a new subscription each time. Signals accumulating unbounded arrays from a live feed. Effects created outside an injection context with an injector that outlives the component. And root effects holding references to component state — a root-provided service’s effect lives for the application’s lifetime.
“Why did asReadonly() not stop that mutation?”
Because it only removes set and update — it does not freeze the value. Deep mutation of the underlying object still works, and worse, it does not notify anyone, so consumers show stale data. Type the value as Readonly<T> so TypeScript catches it, and treat signal values as immutable by convention.
Related pages
Section titled “Related pages”- Change Detection and Zoneless Angular
- Control Flow:
@if,@for,@switch,@defer - Angular Testing: From First Test to Large Suites
- Angular Versions and Release Cadence