javascript / intermediate
Snippet
Derived State with Computed Signals
Computed signals allow you to define reactive state that is derived from other signals. They are lazily evaluated and memoized, meaning the calculation only runs when the underlying signals change and the value is actually read.
snippet.js
1
2
3
4
5
6
7
8
9
10
import { signal, computed } from '@angular/core';@Component({...})export class CartComponent {price = signal(100);quantity = signal(2);// Computed signal automatically updates when price or quantity changestotal = computed(() => this.price() * this.quantity());}
angular
Breakdown
1
price = signal(100);
Initializes a writable signal with a numeric value.
2
total = computed(...);
Creates a read-only signal that derives its value from other signals.