How to Use Signal in Angular: Simple Guide with Examples
In Angular,
signal creates a reactive state container that updates the UI automatically when its value changes. You define a signal with signal(initialValue) and read or update it using signal() or signal.set(newValue) respectively.Syntax
The signal function creates a reactive value that Angular tracks for changes. You initialize it with a starting value. To get the current value, call the signal as a function. To update it, use the set() method.
const count = signal(0);— creates a signal with initial value 0.count()— reads the current value.count.set(5);— updates the value to 5 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 count.set(5); // update value to 5
Output
0
Example
This example shows a simple Angular component using signal to track a counter. The UI updates automatically when the button is clicked.
typescript
import { Component, signal } from '@angular/core'; @Component({ selector: 'app-counter', template: ` <h1>Counter: {{ count() }}</h1> <button (click)="increment()">Increment</button> ` }) export class CounterComponent { count = signal(0); // signal holding the count value increment() { this.count.set(this.count() + 1); // update signal value } }
Output
Counter: 0 (initially)
When clicking 'Increment', the number increases by 1 each time.
Common Pitfalls
Common mistakes when using signal include:
- Trying to update the signal 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()). - Not importing
signalfrom@angular/core.
typescript
/* Wrong way: */ const count = signal(0); count = 5; // Error: cannot assign directly /* Right way: */ count.set(5); // Correct update /* Wrong way to read value: */ console.log(count); // Outputs function, not value /* Right way to read value: */ console.log(count()); // Outputs current value
Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Create signal | const state = signal(initialValue); | Creates a reactive signal with initial value. |
| Read value | state() | Gets the current value of the signal. |
| Update value | state.set(newValue); | Sets a new value and triggers updates. |
| Update with function | state.update(old => newValue); | Updates value based on previous value. |
Key Takeaways
Use
signal(initialValue) to create reactive state in Angular.Read the signal value by calling it as a function:
signal().Update the signal value with
signal.set(newValue) or signal.update(fn).Never assign directly to the signal variable; always use
set or update.Signals automatically update the UI when their value changes.