Signals provide a simpler way to manage reactive data in Angular. Migrating from observables to signals helps write cleaner and more efficient code.
0
0
Migrating from observables to signals in Angular
Introduction
You want to simplify your component's reactive data handling.
You are updating an Angular app to use the latest reactive features.
You want to reduce boilerplate code for subscriptions and unsubscriptions.
You want better performance with automatic change detection.
You want to improve code readability and maintainability.
Syntax
Angular
const signalName = signal(initialValue); // To update the signal signalName.set(newValue); // To read the signal value const value = signalName();
Signals are functions that hold a value and notify when it changes.
Use signal() to create a signal with an initial value.
Examples
This creates a signal
count starting at 0, updates it to 5, then logs 5.Angular
import { signal } from '@angular/core'; const count = signal(0); count.set(5); console.log(count());
Signal
userName holds a string and can be read by calling it as a function.Angular
import { signal } from '@angular/core'; const userName = signal('Alice'); // Reading the signal console.log(userName());
Boolean signals can track states like login status.
Angular
import { signal } from '@angular/core'; const isLoggedIn = signal(false); // Update signal when user logs in isLoggedIn.set(true);
Sample Program
This Angular component uses a signal count to track a number. Clicking the button increases the count. The template updates automatically when the signal changes.
Angular
import { Component, signal } from '@angular/core'; @Component({ selector: 'app-counter', standalone: true, template: ` <h2>Counter: {{ count() }}</h2> <button (click)="increment()">Increment</button> ` }) export class CounterComponent { count = signal(0); increment() { this.count.set(this.count() + 1); } }
OutputSuccess
Important Notes
Signals automatically trigger Angular's change detection when updated.
Unlike observables, signals do not require manual subscription or unsubscription.
Use signals for simpler reactive state management in Angular components.
Summary
Signals replace observables for simpler reactive data handling.
Use signal() to create reactive values that update the UI automatically.
Migrating reduces code complexity and improves performance.