AI Hints
Home›Angular Tutorial›computed(), effect() and Signals with Arrays
Angular · Lesson 31 of 120

computed()

Values from values.

⏱ 2 min read▶ Video at 37:35🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Some values are worked out from other values. A total is the price, times the quantity. Angular has a special signal for this, computed.

  • Values from values
  • Total = price × quantity
  • computed

Computed signals

Computed takes a function, that reads other signals. It works out its value from them. When any of them change, it works the value out again, automatically. And you can't set a computed signal, it's read only.

keyvalue
computed(() => ...)a derived value
Readsother signals
Updatesautomatically
Read onlyno set, no update

A basket total

Price, and quantity, are normal signals. Total is computed, from price times quantity. Delivery is computed from the total, and it's free from twenty five pounds. We click add a copy twice. Run it. Three copies cost thirty two ninety seven. So delivery became free, without any extra code.

app.tstypescript
import { Component, signal, computed } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h2>Circe · £{{ price() }}</h2>
    <button (click)="quantity.update(q => q + 1)">Add a copy</button>
    <p>Copies: {{ quantity() }}</p>
    <p>Total: £{{ total().toFixed(2) }}</p>
    <p>{{ delivery() }}</p>
  `,
})
export class App {
  price = signal(10.99);
  quantity = signal(1);
  total = computed(() => this.price() * this.quantity());
  delivery = computed(() => (this.total() >= 25 ? 'Free delivery!' : 'Delivery £2.99'));
}
Also uses actions.json
[{"click": "button", "times": 2}]

Why not a method?

A method runs every time it's called. A computed signal remembers its value, and only works it out again when its inputs change. So computed is faster, and it makes clear what the value depends on.

keyvalue
Methodruns on every call
computedremembers its value
Recalculatesonly when inputs change
Clearshows its inputs

Summary

Computed works out a value from other signals, updates by itself, and is read only. Next, effects.

Key takeaways
  • computed()
  • Automatic
  • Read only
Next up: effect() — run code when signals change