Angular Signals

Exploring the new Angular Signals features.

Published: 6/6/2024

Angular has two types of Signals:

  1. Writable signal:
    • Don’t depend on other signals.
    • Can directly set a value.
  2. Computed signal:
    1. Do depend on other signals (both writable or computed).
    2. Can’t directly set a value.

Angular has effect, which can be called in the constructor, and runs on the signal set/update.

If a signal isn’t read then Angular won’t watch changes to it, e.g. when inside an unreachable code branch. See video for more info on this in particular, toward the end.

<div>Total: ${{ total() }} <button (click)="add()">Add 10</button></div>
// Writable signals
id = signal(0);
quantity = signal(1);
// Computed signal
total = computed(() => this.quantity() * 10);

add() {
  // The next two lines have the same outcome
  this.quantity.set(this.quantity() + 1);
  this.quantity.update((value) => value + 1);
  // this.id.set(Math.random());
}

constructor() {
  // Executes once, only after the signal update phase whereby all values have been computed
  // Everytime a signal value is changed, all effect contents are run, i.e. only one signal needs to have changed, quantity | total | id
  effect(() => {
    console.log('Quantity:', this.quantity());
    console.log('Total:', this.total());
    console.log(this.id());
  });

  // Only executes when id changes
  // Cannot change a signal value inside an effect, specified as allowed
  effect(
    () => {
      console.log('Id by itself:', this.id());
      this.id.set(10);
    },
    { allowSignalWrites: true }
  );
}

// Effect can be assigned to a class property
useEffect = effect(() => {});
  • import { computed, effect, signal } from '@angular/core';