Signals: Angular's Modern Reactivity Model
7 min read
Signals: Angular's Modern Reactivity Model
"Change is the only constant." — Heraclitus (and also your Front-End State)
Welcome to the modern era of Angular. If you have been using Angular for a while, you are likely familiar with Zone.js—the invisible magic that tells Angular when to update the DOM. While effective, it is a blunt instrument. It checks everything, everywhere, all at once.
Signals represent a paradigm shift toward fine-grained reactivity. Instead of checking the entire component tree, Angular can now pinpoint exactly which text node or binding needs to update.
This guide will take you from the absolute basics of reactive primitives to complex interoperability with RxJS.
1. Introduction to Signals: Writable vs. Read-Only
The Concept
A Signal is a wrapper around a value that can notify interested consumers when that value changes. Technically, a signal is a function that returns the current value when called, and (if writable) allows modification.
The Problem
In standard Angular (Zone-based), change detection relies on monkey-patching browser events (clicks, timeouts, HTTP). When an event occurs, Angular checks the entire component tree to see if data changed.
- Issue: This is computationally expensive for large applications.
- Issue: It makes it difficult to understand exactly what triggered an update.
The Solution
Signals introduce a dependency graph. If a value changes, only the things that depend on that specific value are notified.
Writable Signals
A WritableSignal allows you to directly modify its value.
Syntax:
import { signal, WritableSignal } from '@angular/core';
// 1. Initialize
const count: WritableSignal<number> = signal(0);
// 2. Read (It's a function!)
console.log(count()); // Output: 0
// 3. Write
count.set(5);Modifying State: set vs update
There are two distinct ways to change a signal:
.set(value): Replaces the value entirely. Use this when the new value does not depend on the old one..update(fn): Computes a new value based on the current value. Use this for toggles, counters, or appending to arrays.
Example:
// Replace entirely
const username = signal('Guest');
username.set('Developer');
// Update based on previous
const counter = signal(0);
counter.update(currentValue => currentValue + 1);Read-Only Signals
Sometimes, you want to expose a signal to a child component or a template, but you do not want them to modify it.
The Solution: Use .asReadonly().
const _secretKey = signal('XYZ-123');
// Publicly exposed as ReadOnlySignal<string>
readonly secretKey = this._secretKey.asReadonly();
// _secretKey.set('New') -> Works
// secretKey.set('New') -> Compiler ErrorIndustry Standard: It is common practice in services to keep the
WritableSignalprivate and expose aReadonlySignalto components to enforce unidirectional data flow.
2. Computed Signals: Deriving State Efficiently
The Problem
You often have state that depends on other state.
- Example:
firstName+lastName=fullName. - Legacy approach: Using a getter (
get fullName()).- Flaw: Getters run on every change detection cycle, even if the names didn't change.
- RxJS approach:
combineLatest([first$, last$]).pipe(map(...)).- Flaw: High boilerplate and mental overhead.
The Solution
Computed Signals define a value that is derived from other signals.
Key Characteristic: Memoization
A computed signal is memoized. This means it calculates its value the first time it is read. If you read it again, and its dependencies haven't changed, it returns the cached value immediately without recalculating.
Implementation
import { signal, computed } from '@angular/core';
const price = signal(100);
const quantity = signal(2);
// Computed signal
const total = computed(() => {
return price() * quantity();
});
console.log(total()); // 200
// Update dependency
price.set(150);
// Total automatically updates
console.log(total()); // 300Dynamic Dependency Tracking
This is a sophisticated feature. If a signal is inside an if statement and that branch is not taken, the signal is no longer tracked as a dependency.
const showPrefix = signal(false);
const prefix = signal('Dr.');
const name = signal('Strange');
const displayName = computed(() => {
if (showPrefix()) {
return `${prefix()} ${name()}`;
} else {
return name();
}
});
// Initially, showPrefix is false.
// 'prefix' is NOT tracked. Changing prefix() will NOT trigger displayName to re-evaluate.Fun Fact: This concept stems from "Push-Pull" reactivity. Angular pushes a notification that "something changed," but the consumer pulls the new value only when needed. It is a lazy evaluation strategy that saves massive amounts of CPU cycles. 🧠
3. Effects: Handling Side-Effects with Signals
The Definition
A side-effect is an operation that interacts with the outside world:
- Logging to the console.
- Writing to
localStorage. - Manually manipulating the DOM (avoid this if possible).
The Problem
We need a way to run code automatically whenever a specific signal changes. In standard programming, we would manually call a function after setting a variable. In reactive programming, we want the variable change to trigger the function.
The Solution
The effect() function.
An effect runs at least once (initially) and then re-runs whenever any signal read inside it notifies of a change.
import { signal, effect } from '@angular/core';
export class ThemeComponent {
theme = signal('light');
constructor() {
// Register the effect
effect(() => {
const currentTheme = this.theme();
console.log(`Theme changed to: ${currentTheme}`);
// Real-world use case: Sync to LocalStorage
localStorage.setItem('user-theme', currentTheme);
});
}
toggle() {
this.theme.update(t => t === 'light' ? 'dark' : 'light');
}
}Important Constraints
- Injection Context: Effects must typically be created in the
constructoror initialized where an injection context is available. - No Signal Setting: By default, Angular prevents you from setting a signal inside an effect. This prevents infinite loops (Signal A triggers Effect -> Effect sets Signal A -> Loop).
- Workaround: If absolutely necessary, you can pass
{ allowSignalWrites: true }in the options, but this is generally discouraged.
- Workaround: If absolutely necessary, you can pass
Imagination Check: Think of
effect()as a security guard monitoring a specific hallway (the signals you read). The guard sleeps until someone walks down that specific hallway. If someone walks down a different hallway, the guard keeps sleeping.
4. Interoperability: Combining Signals with RxJS
The Context
Angular has a deep history with RxJS (Observables). The HttpClient, Router events, and ReactiveForms all use Observables. Signals are not meant to replace RxJS entirely, but to simplify synchronous state management.
The Problem
We have an Observable (e.g., an HTTP stream) but we want to use the convenient syntax of Signals in our template, or vice versa.
The Solution
The @angular/core/rxjs-interop package provides two critical functions: toSignal and toObservable.
1. toSignal: Observable → Signal
This allows you to subscribe to an Observable and read its latest value as a signal. It automatically handles cleanup (unsubscribing) when the component is destroyed.
Use Case: Fetching data from an API.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
@Component({ ... })
export class UserComponent {
private http = inject(HttpClient);
// Observable
private user$ = this.http.get<{ name: string }>('/api/user');
// Converted to Signal
// initialValue is required because Observables are async, but Signals must always have a value.
user = toSignal(this.user$, { initialValue: { name: 'Loading...' } });
// In template: {{ user().name }}
// No need for | async pipe!
}2. toObservable: Signal → Observable
Sometimes you need the power of RxJS operators (like debounceTime, switchMap) on a Signal.
Use Case: Search bar debouncing.
import { signal, inject } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { debounceTime, switchMap } from 'rxjs/operators';
export class SearchComponent {
query = signal(''); // Bound to input
// Convert signal to observable stream
query$ = toObservable(this.query);
results$ = this.query$.pipe(
debounceTime(300), // Wait for user to stop typing
switchMap(q => this.searchService.search(q))
);
}Summary of Best Practices
- Use Signals for synchronous state: User interfaces, counters, toggles, and derived data.
- Use RxJS for asynchronous events: HTTP requests, websocket streams, and complex timing (debouncing).
- Use
computedliberally: It is the most efficient way to handle derived data. - Avoid side effects: Only use
effect()when you actually interact with something outside Angular (DOM, LocalStorage, etc.).
📚 References & Further Reading
- Official Documentation: Angular Signals Guide
- RxJS Interop: RxJS Interop Guide
- API Reference: WritableSignal Interface
Challenge
Challenge: Implement a Reactive Product Filter Service
Your task is to implement an Angular service (ProductService) that manages a list of products using Angular Signals for state management and reactivity. You will need to manage the product list, filter criteria, derive a filtered list, and log changes as a side-effect.
Requirements:
- Inside the
ProductServiceclass, initialize a privateWritableSignalnamedproductsSignalwith the providedinitialProductsdata. - Expose the product list to consumers of the service as a public
ReadonlySignalnamedproducts. This will prevent external components from directly modifying the list. - Create two public
WritableSignals:searchTerm(initialized to an empty string) andminPrice(initialized to0). - Implement a
computedsignal namedfilteredProducts. This signal must derive its value fromproducts,searchTerm, andminPrice. The filtering logic should be case-insensitive for the product name and should only include products with a price greater than or equal tominPrice. - Within the
constructor, create aneffectthat tracks thefilteredProductssignal. Whenever the filtered list changes, it should log a message to the console in the format:Filtered product count: X, whereXis the number of items in the filtered list. - Implement the
addProductmethod. This method should take a newProductobject and add it to theproductsSignallist. Use theupdatemethod of the signal to ensure the state is updated immutably.
Expected result
Your final code should be a fully implemented ProductService class that correctly uses Angular Signals.
Specifically, the solution must contain:
- A private
productsSignalinitialized usingsignal(this.initialProducts). - A public
productsproperty assigned the value ofthis.productsSignal.asReadonly(). - Public
searchTermandminPriceproperties initialized asWritableSignals usingsignal('')andsignal(0)respectively. - A
computedsignal,filteredProducts, that correctly reads the values from the other signals (e.g.,this.products(),this.searchTerm()) and returns a new array ofProductobjects that match both the search term and minimum price criteria. - An
effectin the constructor that callsconsole.log("Filtered product count: " + this.filteredProducts().length). - An
addProductmethod that usesthis.productsSignal.update(currentProducts => [...currentProducts, product])to add a new product immutably.