SupportWriter space ↗
← Back to the journal
Angular

Calculate a Cart Total with Angular Signals and computed

Use a writable signal for quantity and computed for a cart total that follows its changes.

DAdministrator · 20 Sep 2026 · 2 min read

You are reading a translated version.

When quantity changes, a cart subtotal should change with it. Keeping quantity and subtotal as separate writable values can let them drift apart. Store the source data and derive the subtotal.

This example uses whole rupiah values and starts with one item. A computed signal reads the quantity and derives the subtotal, without a manual subscription or an effect that rewrites another state value.

Implementation example

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

@Component({
  selector: 'app-cart-counter',
  standalone: true,
  template: `
    <p>Quantity: {{ quantity() }}</p>
    <button (click)="decrease()" [disabled]="quantity() <= 1">−</button>
    <button (click)="increase()">+</button>
    <p>Total: Rp {{ total() }}</p>
  `,
})
export class CartCounter {
  readonly price = 25000;
  quantity = signal(1);
  total = computed(() => this.price * this.quantity());

  increase(): void {
    this.quantity.update(value => value + 1);
  }

  decrease(): void {
    this.quantity.update(value => Math.max(1, value - 1));
  }
}

Check the result

The initial total is 25000. Pressing plus twice should produce quantity 3 and total 75000. Decrement stops at one; the method enforces that boundary as well as the disabled button.

If a price can change after an API response, store it in a signal and read price() inside the computed value. Avoid mutating signal-held objects without updating their signal.

Example boundary

This calculation is for display. The server must calculate prices and totals again when creating an order. Browser-provided totals must not determine the final charge.

Reference

Official documentation

← Explore more notes