Signals are Angular’s approach to state. Signals are usually used within the class of a component.
Use signal.set()
to set the state value in general.
Use signal.update()
to update the value based on the previous one.
number = signal(0);
increment() {
this.number.update(n => n + 1);
}
Computed signals
Use computed signals, for creating a signal based on another signal
import { signal, computed } from '@angular/core';
number = signal(0);
doubleNumber = computed(() => this.number() * 2);
Arrays and objects
Creating a signal-array:
todoList = signal<string[]>(['Learn Angular', 'Learn React', 'Learn Vue']);
Iterating over the list:
<ul>
<li *ngFor="let todo of todoList()">
{{ todo }}
<button (click)="removeTodo(todo)">X</button>
</li>
</ul>
Types
You can the WritableSignal type for a signal which is updatable:
number: WritableSignal<number> = signal(0);
doubleNumber = computed(() => this.number() * 2);
increment() {
this.number.update(n => n + 1);
}