In Angular 16 Signals were introduced in developer preview. From the documentation:

“A signal is a wrapper around a value that can notify interested consumers when that value changes. Signals can contain any value, from simple primitives to complex data structures.”

Perfect! It seems I can use it in an State Store for change tracking state objects.

A State Store with Angular Signals part II

The CounterStateStore from the last post is completed. In this post I am going to connect the store to some user interface.

I have created both a controls component and a display component.

The controls component

The controls component just contains some buttons. Each button is connected to a click event handler which calls an action on the counter state store.

<button (click)="increment()">Increment</button>
<button (click)="decrement()">Decrement</button>
<button (click)="reset()">Reset</button>
import { Component } from '@angular/core';
import { CounterStateStore } from '../../state-stores counter-state-store'

@Component({
  selector: 'app-controls',
  templateUrl: './controls.component.html',
  styleUrls: ['./controls.component.css']
})
export class ControlsComponent {

  constructor(private counterStateStore: CounterStateStore) {
  }
  
  public increment(): void {
    this.counterStateStore.increment();
  }

  public decrement(): void {
    this.counterStateStore.decrement();
  }

  public reset(): void {
    this.counterStateStore.reset();
  }
}

The display component

The display component then shows the current value of the counter. There is no dependency on the controls component, they are loosly coupled. All communication between the two components is done by sharing the CounterStateStore object. By using Signals there is no need to use RXJS Observables anymore.

<h1>{{ counterValue().counter }}</h1>
import { Component, Signal } from '@angular/core';
import { CounterStateStore } from '../../state-stores/counter-state-store';
import { CounterState } from 'src/app/state/counter-state';

@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class DisplayComponent {

  constructor(private counterStateStore: CounterStateStore) {
  }

  public get counterValue(): Signal<CounterState> {
    return this.counterStateStore.currentValue;
  }
}

Conclusion: Yes, we can use Signals to build our StateStores, probably best to wait for the final release of Angular Signals before using this in production, but it looks promising for now.