All articles

Front-end10 min read

Signals in Angular 22: signal, computed, effect and beyond

A practical guide to signals in Angular 22: signal, computed, effect, linkedSignal, httpResource, Signal Forms, RxJS and the most common mistakes, with tested code.

Also in Português, Español, Français

Signals arrived in Angular 16 as something new and, in Angular 22, became the base of almost everything: inputs, template queries, HTTP calls, forms and change detection itself. If you still write Angular with only @Input, BehaviorSubject and the async pipe, you're using a framework that has already changed underneath you.

This post goes from the basics to what just became stable: signal, computed, effect, linkedSignal, httpResource, signals in components, the bridge with RxJS and Signal Forms. At the end, the most common mistakes.

An honest note: all the code was compiled on Angular 22.3, and every behavior the text claims has a passing test, including a gotcha I only found because the test failed.

TL;DR#

  • signal holds state. Read it by calling it (count()), change it with set or update.
  • computed derives a value from other signals. It's lazy, caches the result and can't be changed.
  • effect is for side effects: saving to localStorage, calling an outside library. Never for changing another signal.
  • linkedSignal is a derived value you can also change, and it goes back to the computed value when its source changes.
  • httpResource fetches data and fetches again on its own when the signals it reads change.
  • In Angular 22, httpResource, rxResource and Signal Forms are stable API, and OnPush is the default.
  • Never mutate an object or array in place. items().push(x) notifies nobody. Use update with a new array.

Why signals#

Before, Angular found out what changed by running change detection over the whole tree, with help from zone.js. A signal flips that around: it knows who depends on it. When it changes, it notifies only those dependents, and Angular updates only that part of the screen.

In practice, that gives you three things:

  • Less work on screen, because Angular doesn't need to check components that don't depend on what changed.
  • More predictable code, because a derived value recalculates on its own and never goes stale.
  • Less RxJS for simple things. Screen state becomes a signal. RxJS is still great for streams of events over time.

signal: the state#

import { signal } from '@angular/core';
 
const count = signal(0);
 
count();                     // 0: reading is calling
count.set(5);                // replaces the value
count.update((n) => n + 1);  // computes the next one from the current: 6

In the template, reading works the same: {{ count() }}. Forgetting the parentheses is the number one beginner mistake.

computed: the derived value#

const price = signal(10);
const quantity = signal(2);
const total = computed(() => price() * quantity());
 
total();          // 20
quantity.set(3);
total();          // 30

Three things the test confirms:

  • It's lazy. The function only runs when someone reads total(). Creating the computed runs nothing.
  • It caches the result. Reading total() twice in a row runs the calculation only once.
  • It only recalculates when a dependency changes. And it finds its dependencies on its own, from the signals it read.

And there's no set: a derived value isn't changed by hand. If you feel like changing a computed, you probably want a linkedSignal (further down).

effect: the side effect#

effect(() => {
  localStorage.setItem('last-query', query());
});

An effect runs once and runs again whenever a signal it read changes. It exists to talk to the world outside Angular: localStorage, a chart drawn by a library, a log.

The most common misuse is this:

// Don't: an effect that keeps another signal in sync.
effect(() => total.set(price() * quantity()));
 
// Do: derived state is a computed.
const total = computed(() => price() * quantity());

If the effect only copies or calculates a value and puts it in another signal, swap it for computed or linkedSignal. The result is the same, without an extra cycle and without any chance of getting out of order.

untracked: reading without depending#

Sometimes you want to read a signal inside an effect without it triggering the effect:

effect(() => {
  console.log(`search: ${query()}, page: ${untracked(page)}`);
});

Here, changing query runs the effect. Changing page doesn't, but when the effect runs it reads the current page.

linkedSignal: a derived value you can change#

The classic case: a list of options and the chosen option. The choice belongs to the user, but if the list changes, the choice needs to go back to a value that makes sense.

const options = signal(['small', 'medium', 'large']);
const choice = linkedSignal(() => options()[0]);
 
choice.set('large');            // the user picked one
options.set(['xs', 'xl']);      // the list changed
choice();                       // 'xs': back to the computed value

It also takes a fuller form, with access to the previous value, which shows up in the example in the next section.

httpResource: data that fetches itself#

Putting it all together in a product search component:

product-search.ts
import { httpResource } from '@angular/common/http';
import { Component, computed, effect, linkedSignal, signal } from '@angular/core';
import { Product } from './product';
 
@Component({
  selector: 'app-product-search',
  template: `
    <input #searchBox [value]="query()" (input)="query.set(searchBox.value)" placeholder="Search products" />
 
    @if (products.isLoading()) {
      <p>Searching...</p>
    } @else {
      <p>{{ count() }} results</p>
      @for (product of products.value(); track product.id) {
        <button type="button" [class.selected]="product.id === selected()?.id" (click)="selected.set(product)">
          {{ product.name }}
        </button>
      }
    }
 
    @if (selected(); as product) {
      <p class="selected-name">Selected: {{ product.name }}</p>
    }
  `,
})
export class ProductSearch {
  // State: the source of truth, changed with set() or update().
  protected readonly query = signal(localStorage.getItem('last-query') ?? '');
 
  // Async data: refetches on its own whenever query() changes. Below 2 letters, no request.
  protected readonly products = httpResource<Product[]>(
    () => {
      const q = this.query().trim();
      return q.length < 2 ? undefined : { url: '/api/products', params: { q } };
    },
    { defaultValue: [] },
  );
 
  // Derived and read-only: recalculated only when products change.
  protected readonly count = computed(() => this.products.value().length);
 
  // Derived but writable: the user picks one, and a new result list resets the choice
  // (keeping it only if the same product is still in the list). While a new search is
  // loading, value() falls back to defaultValue, so that moment is ignored (null source).
  protected readonly selected = linkedSignal<Product[] | null, Product | null>({
    source: () => (this.products.isLoading() ? null : this.products.value()),
    computation: (products, previous) => {
      if (products === null) return previous?.value ?? null;
      return products.find((p) => p.id === previous?.value?.id) ?? null;
    },
  });
 
  constructor() {
    // Side effect: talks to something outside Angular. Never use it to set another signal.
    effect(() => localStorage.setItem('last-query', this.query()));
  }
}

What happens here:

  • query is the state: the typed text.
  • httpResource reads query() and, on every change, makes the request again. If the function returns undefined, it makes no request at all: that's how the search waits for at least two letters. It exposes value(), isLoading() and error() as signals.
  • count is a simple computed on top of the result.
  • selected is a linkedSignal with access to the previous value: the user picks a product, and when a new list arrives the choice only stays if the same product is still in it.
  • The effect saves the last search to localStorage, which lives outside Angular.
Each value knows what it depends on. When query changes, only what depends on it moves

The gotcha the test caught#

In the first version, the linkedSignal used products.value() directly as its source, and the selection disappeared every time the user refined the search, even with the product still in the new list.

The reason: while httpResource fetches again, value() falls back to defaultValue, the empty list. The linkedSignal saw the empty list, didn't find the product and cleared the choice. When the results arrived, the previous value was already null.

The fix is in the code above: while isLoading() is true, the source becomes null, and the function keeps the previous value. This applies to any value derived from a resource: remember that intermediate moment exists.

Signals in components#

Component APIs are signals now too:

BeforeNowWhat it is
@Input() namename = input<string>()component input, read with name()
@Input({ required: true })input.required<string>()required input, build error if missing
@Output() + EventEmitteroutput<string>()event (not a signal, but same style)
@Input + @Output xChangemodel<string>()two-way value with [(x)]
@ViewChild('ref')viewChild<ElementRef>('ref')template query, read as a signal

A viewChild example:

toolbar.ts
import { Component, ElementRef, viewChild } from '@angular/core';
 
@Component({
  selector: 'app-toolbar',
  template: `<input #search placeholder="Search" /> <button type="button" (click)="focusSearch()">Focus</button>`,
})
export class Toolbar {
  // Signal query: the element is read like any other signal.
  private readonly search = viewChild.required<ElementRef<HTMLInputElement>>('search');
 
  protected focusSearch() {
    this.search().nativeElement.focus();
  }
}

Since input() is a signal, you can use it inside computed, and the component reacts on its own when the parent changes the value. You no longer need ngOnChanges for that.

Signals and RxJS#

Signals don't replace RxJS. They cover state. RxJS is still better for streams of events over time: debounce, cancelling the previous request, combining sources. The bridge is the @angular/core/rxjs-interop package:

rx-interop.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
import { rxResource, toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, fromEvent, map } from 'rxjs';
import { Product } from './product';
 
@Component({
  selector: 'app-rx-interop',
  template: `
    <p>Window width: {{ width() }}px</p>
    <input #box (input)="term.set(box.value)" />
    <p>{{ results.value()?.length ?? 0 }} results</p>
  `,
})
export class RxInterop {
  private readonly http = inject(HttpClient);
 
  // Observable to signal: a stream of browser events becomes a value the template reads.
  protected readonly width = toSignal(
    fromEvent(window, 'resize').pipe(map(() => window.innerWidth)),
    { initialValue: window.innerWidth },
  );
 
  // Signal to observable: use RxJS where it shines, like debounce.
  protected readonly term = signal('');
  private readonly debouncedTerm = toSignal(
    toObservable(this.term).pipe(debounceTime(300), distinctUntilChanged()),
    { initialValue: '' },
  );
 
  // A resource whose loader returns an Observable.
  protected readonly results = rxResource({
    params: () => this.debouncedTerm() || undefined,
    stream: ({ params }) => this.http.get<Product[]>('/api/products', { params: { q: params } }),
  });
}
  • toSignal turns an Observable into a signal. Here, the window resize event becomes a value the template reads.
  • toObservable goes the other way, to apply debounceTime to a signal.
  • rxResource is a resource whose loader returns an Observable. Stable since Angular 22.

Signal Forms#

Since Angular 22, forms have a signals version too, and it's stable API. The model is a plain signal, and the form reads and writes straight into it:

sign-up-form.ts
import { Component, signal } from '@angular/core';
import { email, form, FormField, minLength, required } from '@angular/forms/signals';
 
interface SignUp {
  name: string;
  email: string;
  password: string;
}
 
@Component({
  selector: 'app-sign-up-form',
  imports: [FormField],
  template: `
    <label>Name <input [formField]="signUpForm.name" /></label>
    <label>Email <input type="email" [formField]="signUpForm.email" /></label>
    @for (error of signUpForm.email().errors(); track error.kind) {
      <p class="error">{{ error.message }}</p>
    }
    <label>Password <input type="password" [formField]="signUpForm.password" /></label>
    @for (error of signUpForm.password().errors(); track error.kind) {
      <p class="error">{{ error.message }}</p>
    }
    <button type="button" [disabled]="!signUpForm().valid()">Create account</button>
  `,
})
export class SignUpForm {
  // The model is a plain signal: the form reads and writes straight into it.
  protected readonly model = signal<SignUp>({ name: '', email: '', password: '' });
 
  protected readonly signUpForm = form(this.model, (path) => {
    required(path.name, { message: 'Tell us your name' });
    required(path.email, { message: 'Email is required' });
    email(path.email, { message: 'Enter a valid email' });
    minLength(path.password, 8, { message: 'Use at least 8 characters' });
  });
}
  • form(model, rules) creates a tree of fields with the same shape as the model.
  • The rules (required, email, minLength) live in a function, away from the template.
  • [formField] binds each field to an <input>, both ways.
  • Each field's state is a signal: signUpForm.email().errors(), signUpForm().valid().

Reactive Forms still work. For a new form, Signal Forms are shorter and talk directly to the rest of your signal-based code.

What about OnPush and zone.js?#

Two direct consequences of all this in Angular 22:

  • OnPush is the default. A component is only checked when an input changes, an event happens in its template or a signal it reads changes. With signals, this works without you thinking about it.
  • New projects start without zone.js. Angular no longer needs to intercept every setTimeout and every promise to know something changed: signals tell it.

That also explains the most annoying mistake when migrating: state kept in a plain property, changed inside a setTimeout, may not show up on screen. The fix is to keep it in a signal.

Common mistakes#

  • Forgetting the parentheses. {{ count }} shows the function, not the value. It's {{ count() }}.
  • Mutating in place. items().push(x) notifies nobody, and the test confirms it: the computed that depends on the list keeps the old length. Use items.update((list) => [...list, x]).
  • An effect to sync state. If it only does other.set(...), it's a computed or a linkedSignal.
  • Reading a signal after an await. Inside computed and effect, only what was read synchronously counts as a dependency. What comes after an await isn't tracked.
  • Forgetting the loading moment. A value derived from a resource goes through the loading state, when value() falls back to the default.
  • Swapping all RxJS for signals. Debounce, cancellation and combining streams are still RxJS work.

Checklist#

  • State in signal, derived values in computed, outside effects in effect.
  • No effect that only copies a value into another signal.
  • Arrays and objects always replaced with new ones, through update.
  • Server data with httpResource or rxResource, handling isLoading() and error().
  • linkedSignal for a user choice that depends on a list.
  • Inputs with input() and input.required(), events with output(), two-way with model().
  • RxJS only where there's a stream over time, connected with toSignal and toObservable.
  • New forms with Signal Forms.

References#

Written by

Software engineer and designer. I write about what I run into while building apps, APIs and products.

Comments

Sign in with your GitHub account to comment.