Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 74 ยท Projects

Project: Shopping Cart and Checkout

Build an Angular shopping cart in four steps - a signal-based cart service, computed totals, a route guard for checkout and a reactive checkout form. Includes runnable cart logic.

A shopping cart looks simple until you list its rules. Quantities must stay sensible, the total must always agree with the lines, shipping depends on the subtotal, the checkout page makes no sense with an empty cart, and the checkout form has to catch mistakes before an order is placed. That mix of shared state, derived values, routing and forms is why a cart is a perfect Angular project.

We build it in four steps: a cart service holding state in signals, computed totals, a guard that protects /checkout, and a reactive form for the address and terms. The ideas come from State Management with Signals and Services, Guards, Resolvers and Router Events and Reactive Forms.

Real versus stand-in. The typescript and html blocks are real Angular and read-only, because this site cannot run the Angular compiler. The runnable examples rebuild the logic (cart rules, a tiny signal implementation, a mini router with a guard, form validation) as plain TypeScript, so you can run and change it. They are simplified models, not Angular itself.

The plan

flowchart LR
  List["Product list"] -->|"add()"| Cart["CartService<br/>(signals)"]
  Cart --> Page["Cart page<br/>(lines, totals)"]
  Page -->|"Checkout"| Guard{"cartNotEmpty<br/>guard"}
  Guard -->|"has items"| Form["Checkout form<br/>(reactive)"]
  Guard -->|"empty"| Page
  Form -->|"valid submit"| Done["Confirmation<br/>(cart cleared)"]

One service owns the cart. Pages read it; the guard and the form decide whether the user may move forward.

Step 1: a cart service built on signals

The cart has one piece of real state: a list of lines, each with a product id and a quantity. Everything else (item count, subtotal, shipping, total) can be computed from that list, so it is never stored. If you stored a total next to lines, one day the two would disagree.

Two decisions are worth stating early. Money is kept in integer cents, because 0.1 + 0.2 is 0.30000000000000004 in JavaScript and prices must add up exactly. And updates are immutable: the signal gets a new array each time, instead of the old array being changed in place, so dependents notice the change (see Signals: signal, computed and effect).

TypeScript
// cart.service.ts
import { Injectable, computed, signal } from '@angular/core';

export interface Product {
  id: string;
  name: string;
  priceCents: number;
}

export interface CartLine {
  product: Product;
  quantity: number;
}

const MAX_QUANTITY = 10;
const FREE_SHIPPING_FROM = 5000;   // cents
const SHIPPING_FEE = 499;          // cents
const TAX_RATE = 0.08;

@Injectable({ providedIn: 'root' })
export class CartService {
  private readonly linesState = signal<readonly CartLine[]>([]);

  readonly lines = this.linesState.asReadonly();

  readonly itemCount = computed(() =>
    this.linesState().reduce((sum, line) => sum + line.quantity, 0),
  );

  readonly subtotalCents = computed(() =>
    this.linesState().reduce((sum, line) => sum + line.product.priceCents * line.quantity, 0),
  );

  readonly shippingCents = computed(() => {
    const subtotal = this.subtotalCents();
    return subtotal === 0 || subtotal >= FREE_SHIPPING_FROM ? 0 : SHIPPING_FEE;
  });

  readonly taxCents = computed(() => Math.round(this.subtotalCents() * TAX_RATE));

  readonly totalCents = computed(
    () => this.subtotalCents() + this.shippingCents() + this.taxCents(),
  );

  add(product: Product): void {
    this.linesState.update(lines => {
      const existing = lines.find(line => line.product.id === product.id);
      if (!existing) {
        return [...lines, { product, quantity: 1 }];
      }
      return lines.map(line =>
        line === existing
          ? { ...line, quantity: Math.min(line.quantity + 1, MAX_QUANTITY) }
          : line,
      );
    });
  }

  setQuantity(productId: string, quantity: number): void {
    this.linesState.update(lines =>
      quantity <= 0
        ? lines.filter(line => line.product.id !== productId)
        : lines.map(line =>
            line.product.id === productId
              ? { ...line, quantity: Math.min(quantity, MAX_QUANTITY) }
              : line,
          ),
    );
  }

  clear(): void {
    this.linesState.set([]);
  }
}

The private linesState can be written only inside the service. Components receive lines, a read-only view made with asReadonly(), so no component can sneak in and change the cart without going through add, setQuantity or clear. Each computed depends on the signals it reads, caches its result and only recalculates when the lines change.

The first runnable example models this service. Because the real computed() is built into Angular, the example contains a very small signal and computed of its own (about 25 lines) and counts how often the subtotal is actually calculated.

TypeScript Cart logic with signals, computed totals and memoization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Study the lines. Shipping is charged while the subtotal is below $50.00 and disappears when it reaches the limit. Setting a quantity of 99 is clamped to 10, and 0 removes the line. Reading the totals again does no extra work, because every computed is cached until the lines change. The last line shows why the example (and the real service) keeps prices in cents.

Step 2: showing the cart

The cart page is a plain template over the service's signals. Quantity changes go through the service, never through direct edits.

TypeScript
// cart-page.ts
import { CurrencyPipe } from '@angular/common';
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { CartService } from './cart.service';

@Component({
  selector: 'app-cart-page',
  imports: [CurrencyPipe, RouterLink],
  templateUrl: './cart-page.html',
})
export class CartPage {
  protected readonly cart = inject(CartService);

  protected changeQuantity(productId: string, event: Event): void {
    const input = event.target as HTMLInputElement;
    this.cart.setQuantity(productId, input.valueAsNumber);
  }
}
HTML
<!-- cart-page.html -->
<h1>Your cart ({{ cart.itemCount() }})</h1>

@for (line of cart.lines(); track line.product.id) {
  <div class="line">
    <span>{{ line.product.name }}</span>
    <input type="number" min="0" max="10" [value]="line.quantity"
           [attr.aria-label]="'Quantity of ' + line.product.name"
           (change)="changeQuantity(line.product.id, $event)" />
    <span>{{ line.product.priceCents * line.quantity / 100 | currency }}</span>
  </div>
} @empty {
  <p>Your cart is empty.</p>
}

<dl>
  <dt>Subtotal</dt><dd>{{ cart.subtotalCents() / 100 | currency }}</dd>
  <dt>Shipping</dt><dd>{{ cart.shippingCents() / 100 | currency }}</dd>
  <dt>Tax</dt><dd>{{ cart.taxCents() / 100 | currency }}</dd>
  <dt>Total</dt><dd>{{ cart.totalCents() / 100 | currency }}</dd>
</dl>

<a routerLink="/checkout">Go to checkout</a>

The @for uses track line.product.id, so Angular reuses the right row when quantities change or a line is removed (Control Flow). The division by 100 happens only at the edge, when the number is displayed; the stored values stay in cents. currency formats according to the app locale and a default currency code, so configure those for a real shop.

Step 3: protect checkout with a guard

Typing /checkout into the address bar with nothing in the cart should not show a payment form. A functional guard checks the cart and returns either true or a UrlTree that redirects:

TypeScript
// guards.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { CartService } from './cart.service';

export const cartNotEmpty: CanActivateFn = () => {
  const cart = inject(CartService);
  const router = inject(Router);
  return cart.itemCount() > 0 ? true : router.createUrlTree(['/cart']);
};
TypeScript
// app.routes.ts
import { Routes } from '@angular/router';
import { cartNotEmpty } from './guards';

export const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'products' },
  { path: 'products', loadComponent: () => import('./products').then(m => m.Products) },
  { path: 'cart', loadComponent: () => import('./cart-page').then(m => m.CartPage) },
  {
    path: 'checkout',
    canActivate: [cartNotEmpty],
    loadComponent: () => import('./checkout').then(m => m.Checkout),
  },
  { path: 'confirmation/:orderId', loadComponent: () => import('./confirmation').then(m => m.Confirmation) },
  { path: '**', redirectTo: 'products' },
];

Returning a UrlTree is better than calling router.navigate() inside the guard, because the router can cancel the current navigation and start the redirect in one clean step. A guard is a convenience for the user, not security: anyone can change browser code, so the server must still check that an order is valid. Each page is loaded lazily with loadComponent, which keeps the first download small (Child Routes and Lazy Loading).

Step 4: the checkout form

The checkout page uses a reactive form, because the validation rules deserve to live in code where they can be read and tested. NonNullableFormBuilder produces controls whose values are never null, which keeps the types simple.

TypeScript
// checkout.ts
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { CartService } from './cart.service';

@Component({
  selector: 'app-checkout',
  imports: [ReactiveFormsModule],
  templateUrl: './checkout.html',
})
export class Checkout {
  private readonly fb = inject(NonNullableFormBuilder);
  private readonly router = inject(Router);
  protected readonly cart = inject(CartService);

  protected readonly form = this.fb.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    email: ['', [Validators.required, Validators.email]],
    postalCode: ['', [Validators.required, Validators.pattern(/^\d{5}$/)]],
    acceptTerms: [false, Validators.requiredTrue],
  });

  protected submit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    // In a real shop: POST the order, wait for the server's answer, then:
    const orderId = 'A-1001';
    this.cart.clear();
    this.router.navigate(['/confirmation', orderId]);
  }
}
HTML
<!-- checkout.html -->
<form [formGroup]="form" (ngSubmit)="submit()" novalidate>
  <label for="name">Full name</label>
  <input id="name" formControlName="name" autocomplete="name" />
  @if (form.controls.name.touched && form.controls.name.invalid) {
    <p class="error" role="alert">Please enter your name.</p>
  }

  <label for="email">Email</label>
  <input id="email" type="email" formControlName="email" autocomplete="email" />
  @if (form.controls.email.touched && form.controls.email.invalid) {
    <p class="error" role="alert">Please enter a valid email address.</p>
  }

  <label for="zip">Postal code</label>
  <input id="zip" formControlName="postalCode" inputmode="numeric" autocomplete="postal-code" />
  @if (form.controls.postalCode.touched && form.controls.postalCode.invalid) {
    <p class="error" role="alert">Use a 5-digit postal code.</p>
  }

  <label><input type="checkbox" formControlName="acceptTerms" /> I accept the terms</label>

  <button type="submit">Pay {{ cart.totalCents() / 100 | currency }}</button>
</form>

Errors only appear after the field is touched, so the form does not shout at a user who has not typed anything yet. markAllAsTouched() on a failed submit reveals every problem at once. In a real shop, never place the order on the client alone: the server should recompute prices from its own catalog, because a browser can send any number. Card details should go through a payment provider's own components, never through your own inputs.

The second runnable example models steps 3 and 4: a mini router that runs a guard and follows redirects, the same validation rules as the form, and an order that clears the cart.

TypeScript Guard, redirect and checkout validation stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first navigation is blocked and redirected to /cart. With two items the guard lets you in. The invalid form lists every broken field, the valid one places order A-1001, clears the cart and moves on to the confirmation. Trying /checkout once more is blocked again, because the cart is now empty again.

Ideas to extend it

  • Keep the cart across reloads: an effect() in the service writes lines() to localStorage, and the initial value is read in a try/catch. Browser storage does not exist on the server, so guard it when you use server-side rendering.
  • Add a discount code as another signal and make the total depend on it.
  • Use linkedSignal for a "quantity being edited" value that resets when the line changes.
  • Test the service with plain unit tests: it needs no DOM, see Testing Components and Services.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the cart service store only the lines and compute the total?

    Derived values stored separately can drift out of sync. A computed signal is recalculated from the single source of truth and cached.
  2. 2. Why are prices kept as integer cents?

    0.1 + 0.2 is not exactly 0.3 in floating point. Integer cents add up exactly; divide by 100 only when displaying.
  3. 3. What should a canActivate guard return to send the user somewhere else?

    Returning a UrlTree lets the router cancel the current navigation and start the redirect cleanly.
  4. 4. Why can the checkout guard not be your only protection?

    A guard improves the experience, but anything in the browser can be bypassed. Authoritative checks belong on the server.
  5. 5. What does markAllAsTouched() do on a failed submit?

    The template only shows errors for touched controls. After a failed submit, marking everything as touched reveals all problems at once.

Summary

  • Keep the cart's real state (the lines) in a private signal and expose a read-only view plus a few methods.
  • Derive item count, subtotal, shipping, tax and total with computed(); never store them separately.
  • Store money in integer cents and format it only at the edge.
  • A functional canActivate guard returns true or a UrlTree to keep users out of an empty checkout; the server still has the last word.
  • A reactive form with NonNullableFormBuilder keeps the validation rules in code; show errors for touched controls and call markAllAsTouched() on a failed submit.

Next: Project: Blog with Routing and Lazy Routes.