How to Use Signal for State Management in Angular
In Angular, you use
signal to create reactive state variables that automatically update the UI when changed. Define a signal with signal(initialValue), update it with set(), and read its value with signal() or inside templates using Angular's reactive system.Syntax
The signal function creates a reactive state variable. You initialize it with a starting value. Use set(newValue) to update the state, and access the current value by calling the signal as a function.
- signal(initialValue): Creates the reactive state.
- signal(): Reads the current value.
- signal.set(newValue): Updates the value and triggers UI updates.
typescript
import { signal } from '@angular/core'; const count = signal(0); // create signal with initial value 0 console.log(count()); // read current value, outputs 0 count.set(5); // update value to 5 console.log(count()); // outputs 5
Output
0
5
Example
This example shows a simple Angular component using signal to manage a counter state. The UI updates automatically when the counter changes.
typescript
import { Component, signal } from '@angular/core'; @Component({ selector: 'app-counter', template: ` <h2>Counter: {{ count() }}</h2> <button (click)="increment()">Increment</button> ` }) export class CounterComponent { count = signal(0); // create signal with initial value 0 increment() { this.count.set(this.count() + 1); // update signal value } }
Output
User sees a heading 'Counter: 0' initially. Clicking the 'Increment' button increases the number by 1 each time, updating the displayed count instantly.
Common Pitfalls
Common mistakes when using signal include:
- Trying to update the signal value by assigning directly (e.g.,
count = 5) instead of usingcount.set(5). - Reading the signal value without calling it as a function (e.g.,
countinstead ofcount()), which returns the signal object, not the value. - Not importing
signalfrom@angular/core.
Correct usage example:
count.set(count() + 1);
Incorrect usage example:
count = count() + 1; // wrong
Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Create signal | const state = signal(initialValue); | Initialize reactive state with a value |
| Read value | state() | Get current value of the signal |
| Update value | state.set(newValue); | Change value and trigger updates |
| Update with function | state.update(old => newValue); | Update based on previous value |
Key Takeaways
Use
signal(initialValue) to create reactive state in Angular.Always update signals with
set() or update(), never by direct assignment.Read signal values by calling them as functions, like
signal().Signals automatically update the UI when their value changes.
Import
signal from @angular/core to use this feature.