Global State with Signals

In Angular projects, there are many components like header, footer, search, login, cart, etc.

Sometimes data needs to be shared between multiple components.

To share data easily, we store it in one common place called global state.

Global state works like a store.

Components can read data from it and also update data in it.


Counter Global State Example

A service file is created for the counter.

A signal named count is used to store the value.

export class Counter {
count = signal(10)

decrement() {
this.count.update((c) => c - 1)
}

increment() {
this.count.update((c) => c + 1)
}

reset() {
this.count.set(0)
}
}

This service acts as the global store.


Display Component

The display component only shows the counter value.

The service is injected using the constructor.

The signal value is read using count().

<h3>{{state.count()}}</h3>
<button (click)="state.reset()">Reset</button>


Control Component

The control component only controls the counter.

It has increment and decrement buttons.

The same service is injected here too.

<button (click)="state.decrement()">Decrement</button>
<button (click)="state.increment()">Increment</button>


Sharing Data Between Components

Both components use the same service instance.

When one component updates the counter, the other updates automatically.

This happens because the signal is shared globally.