0
0
AngularConceptBeginner · 3 min read

What is Computed Signal in Angular: Explanation and Example

In Angular, a computed signal is a special reactive value that automatically updates when its dependent signals change. It lets you create values derived from other signals without manually managing updates, making your app reactive and efficient.
⚙️

How It Works

A computed signal in Angular works like a smart calculator that watches other values and updates itself whenever those values change. Imagine you have a recipe that depends on ingredients; if any ingredient changes, the recipe updates automatically without you doing anything extra.

Under the hood, Angular tracks which signals a computed signal depends on. When any of those signals change, Angular recalculates the computed signal's value. This helps keep your UI or logic in sync with data changes smoothly and efficiently.

💻

Example

This example shows a computed signal that calculates the full name from first and last name signals. When either name changes, the full name updates automatically.

typescript
import { signal, computed } from '@angular/core';

const firstName = signal('Jane');
const lastName = signal('Doe');

const fullName = computed(() => `${firstName()} ${lastName()}`);

console.log(fullName()); // Outputs: Jane Doe

// Update first name
firstName.set('John');
console.log(fullName()); // Outputs: John Doe
Output
Jane Doe John Doe
🎯

When to Use

Use computed signals when you want to create values that depend on other reactive data and need to update automatically. They are perfect for derived state like combined strings, calculated numbers, or filtered lists.

For example, in a shopping app, you can use computed signals to calculate the total price from item quantities and prices. This way, the total updates instantly when the user changes quantities without extra code.

Key Points

  • Computed signals automatically update when their dependencies change.
  • They help keep your app reactive and reduce manual update code.
  • Use them for derived or calculated state based on other signals.
  • They improve performance by recalculating only when needed.

Key Takeaways

Computed signals in Angular automatically update based on dependent signals.
They simplify managing derived reactive state in your app.
Use computed signals to keep UI and logic in sync without manual updates.
They improve app performance by recalculating only when dependencies change.