Learn Angular · 10/14

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:

typescript
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:

  1. .set(value): Replaces the value entirely. Use this when the new value does not depend on the old one.
  2. .update(fn): Computes a new value based on the current value. Use this for toggles, counters, or appending to arrays.

Example:

typescript
// 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().

typescript
const _secretKey = signal('XYZ-123');
// Publicly exposed as ReadOnlySignal<string>
readonly secretKey = this._secretKey.asReadonly();

// _secretKey.set('New') -> Works
// secretKey.set('New')  -> Compiler Error

Industry Standard: It is common practice in services to keep the WritableSignal private and expose a ReadonlySignal to 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

typescript
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()); // 300

Dynamic 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.

typescript
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.

typescript
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

  1. Injection Context: Effects must typically be created in the constructor or initialized where an injection context is available.
  2. 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.

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.

typescript
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.

typescript
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

  1. Use Signals for synchronous state: User interfaces, counters, toggles, and derived data.
  2. Use RxJS for asynchronous events: HTTP requests, websocket streams, and complex timing (debouncing).
  3. Use computed liberally: It is the most efficient way to handle derived data.
  4. Avoid side effects: Only use effect() when you actually interact with something outside Angular (DOM, LocalStorage, etc.).

📚 References & Further Reading

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:

  1. Inside the ProductService class, initialize a private WritableSignal named productsSignal with the provided initialProducts data.
  2. Expose the product list to consumers of the service as a public ReadonlySignal named products. This will prevent external components from directly modifying the list.
  3. Create two public WritableSignals: searchTerm (initialized to an empty string) and minPrice (initialized to 0).
  4. Implement a computed signal named filteredProducts. This signal must derive its value from products, searchTerm, and minPrice. The filtering logic should be case-insensitive for the product name and should only include products with a price greater than or equal to minPrice.
  5. Within the constructor, create an effect that tracks the filteredProducts signal. Whenever the filtered list changes, it should log a message to the console in the format: Filtered product count: X, where X is the number of items in the filtered list.
  6. Implement the addProduct method. This method should take a new Product object and add it to the productsSignal list. Use the update method 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 productsSignal initialized using signal(this.initialProducts).
  • A public products property assigned the value of this.productsSignal.asReadonly().
  • Public searchTerm and minPrice properties initialized as WritableSignals using signal('') and signal(0) respectively.
  • A computed signal, filteredProducts, that correctly reads the values from the other signals (e.g., this.products(), this.searchTerm()) and returns a new array of Product objects that match both the search term and minimum price criteria.
  • An effect in the constructor that calls console.log("Filtered product count: " + this.filteredProducts().length).
  • An addProduct method that uses this.productsSignal.update(currentProducts => [...currentProducts, product]) to add a new product immutably.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.