Computed signals help you automatically update values when other values change. They keep your app data fresh without extra work.
0
0
Computed signals for derived values in Angular
Introduction
You want to show a total price that updates when item prices change.
You need to display a full name that updates when first or last name changes.
You want to enable or disable a button based on multiple input fields.
You want to calculate a value based on other signals without writing manual update code.
Syntax
Angular
const derivedValue = computed(() => { // return a value based on other signals });
The computed function takes a function that returns a value.
It automatically tracks signals used inside and updates when they change.
Examples
This creates a signal
count and a computed signal doubleCount that is always twice the count.Angular
const count = signal(0); const doubleCount = computed(() => count() * 2);
This computed signal combines two signals to create a full name that updates automatically.
Angular
const firstName = signal('Jane'); const lastName = signal('Doe'); const fullName = computed(() => `${firstName()} ${lastName()}`);
Sample Program
This Angular component shows a shopping cart with an item price and quantity. The total price is a computed signal that updates automatically when quantity changes. Clicking the button increases quantity and updates total.
Angular
import { Component, signal, computed } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-root', standalone: true, imports: [CommonModule], template: ` <h1>Shopping Cart</h1> <p>Item price: {{ itemPrice() | currency }}</p> <p>Quantity: {{ quantity() }}</p> <p><strong>Total: {{ total() | currency }}</strong></p> <button (click)="increase()">Add One</button> ` }) export class AppComponent { itemPrice = signal(10); quantity = signal(1); total = computed(() => this.itemPrice() * this.quantity()); increase() { this.quantity.update(q => q + 1); } }
OutputSuccess
Important Notes
Computed signals only recalculate when their dependencies change, making them efficient.
Use computed inside components or services to keep derived data reactive.
Summary
Computed signals automatically update derived values when dependencies change.
They simplify keeping your UI and data in sync without manual updates.