AI Hints
Home›Angular Tutorial›Project: The Book Page, The Basket and Checkout Form
Angular · Lesson 116 of 120

Project: The Basket

Review the order.

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

The basket page shows everything the customer has added, with a remove button, and the total.

  • Everything added
  • Remove buttons
  • The total

The basket page

At for lists the items, tracked by position, because the same book could be added twice. Each row has a remove button. The total comes from the service. And the checkout link only shows when the basket isn't empty. We add Dune, and Emma, then open the basket. Run it. Both books are listed, with a total of sixteen ninety eight.

basket-page.tstypescript
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { Basket } from './basket';
@Component({
  selector: 'app-basket-page',
  imports: [RouterLink],
  template: `
    <h2>Your basket</h2>
    @for (b of basket.items(); track $index) {
      <p>{{ b.title }} · £{{ b.price }}
        <button (click)="basket.remove($index)">×</button></p>
    } @empty { <p>Your basket is empty.</p> }
    <p><b>Total: £{{ basket.total().toFixed(2) }}</b></p>
    @if (basket.count()) { <a id="checkout" routerLink="/checkout">Go to checkout</a> }
  `,
})
export class BasketPage {
  basket = inject(Basket);
}
Also uses book.ts
export interface Book {
  id: number;
  title: string;
  author: string;
  price: number;
}
Also uses basket.ts
import { Service, signal, computed } from '@angular/core';
import { Book } from './book';

@Service()
export class Basket {
  private readonly list = signal<Book[]>([]);
  readonly items = this.list.asReadonly();
  readonly count = computed(() => this.list().length);
  readonly total = computed(() => this.list().reduce((sum, b) => sum + b.price, 0));

  add(book: Book) { this.list.update(l => [...l, book]); }
  remove(index: number) { this.list.update(l => l.filter((_, i) => i !== index)); }
  clear() { this.list.set([]); }
}
Also uses app.routes.ts
import { Routes } from '@angular/router';
import { BookList } from './book-list';

export const routes: Routes = [
  { path: '', redirectTo: 'books', pathMatch: 'full' },
  { path: 'books', component: BookList },
  { path: 'books/:id', loadComponent: () => import('./book-page').then(m => m.BookPage) },
  { path: 'basket', loadComponent: () => import('./basket-page').then(m => m.BasketPage) },
  { path: 'checkout', loadComponent: () => import('./checkout').then(m => m.Checkout) },
  { path: '**', redirectTo: 'books' },
];
Also uses app.ts
import { Component, inject } from '@angular/core';
import { RouterOutlet, RouterLink } from '@angular/router';
import { Basket } from './basket';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, RouterLink],
  template: `
    <nav class="bar">
      <a id="home" routerLink="/books"><b>Page Turners</b></a>
      <a id="cart" routerLink="/basket">Basket ({{ basket.count() }})</a>
    </nav>
    <router-outlet />
  `,
  styles: `.bar { display: flex; justify-content: space-between; margin-bottom: 8px; }`,
})
export class App {
  basket = inject(Basket);
}
Also uses book-list.ts
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { RouterLink } from '@angular/router';
import { Book } from './book';

@Component({
  selector: 'app-book-list',
  imports: [RouterLink],
  template: `
    <input (input)="q.set($any($event.target).value)" placeholder="Search books">
    @for (b of books.value(); track b.id) {
      <p><a [routerLink]="['/books', b.id]">{{ b.title }}</a> · £{{ b.price }}</p>
    } @empty { <p class="muted">No books found.</p> }
  `,
})
export class BookList {
  q = signal('');
  books = httpResource<Book[]>(() => `/api/books?q=${this.q()}`, { defaultValue: [] });
}
Also uses book-page.ts
import { Component, inject, input } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { Basket } from './basket';
import { Book } from './book';
@Component({
  selector: 'app-book-page',
  template: `
    @if (book.error()) { <p class="error">Book not found.</p> }
    @else if (book.value(); as b) {
      <h2>{{ b.title }}</h2>
      <p>by {{ b.author }} · £{{ b.price }} <button (click)="basket.add(b)">Add</button></p>
    }
  `,
})
export class BookPage {
  basket = inject(Basket);
  id = input.required<string>();
  book = httpResource<Book>(() => `/api/books/${this.id()}`);
}
Also uses checkout.ts
import { Component, inject, signal } from '@angular/core';
import { form, FormField, required, email } from '@angular/forms/signals';
import { Basket } from './basket';
@Component({
  selector: 'app-checkout', imports: [FormField], templateUrl: './checkout.html',
})
export class Checkout {
  basket = inject(Basket);
  done = signal('');
  model = signal({ name: '', email: '' });
  checkout = form(this.model, p => {
    required(p.name); required(p.email); email(p.email);
  });
  order() {
    const paid = this.basket.total().toFixed(2);
    this.done.set(`Thanks, ${this.model().name}! You paid £${paid}.`);
    this.basket.clear();
  }
}
Also uses checkout.html
<h2>Checkout</h2>
@if (done()) {
  <p class="card">{{ done() }}</p>
} @else {
  <input [formField]="checkout.name" placeholder="Name">
  <input [formField]="checkout.email" placeholder="Email">
  <p>To pay: £{{ basket.total().toFixed(2) }}</p>
  <button [disabled]="checkout().invalid()" (click)="order()">Place order</button>
}
Also uses actions.json
[{"click": "p:nth-of-type(1) a"}, {"wait": 700}, {"click": "app-book-page button"}, {"click": "#home"}, {"wait": 700}, {"click": "p:nth-of-type(4) a"}, {"wait": 700}, {"click": "app-book-page button"}, {"click": "#cart"}, {"wait": 700}]
Also uses _url
/books
Also uses _bar
1

Removing a book

Remove takes the item's position, from dollar index. We add the same two books, then remove the first one. Run it. Dune is gone. The total, and the header count, both updated.

basket-page.tstypescript
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { Basket } from './basket';
@Component({
  selector: 'app-basket-page',
  imports: [RouterLink],
  template: `
    <h2>Your basket</h2>
    @for (b of basket.items(); track $index) {
      <p>{{ b.title }} · £{{ b.price }}
        <button (click)="basket.remove($index)">×</button></p>
    } @empty { <p>Your basket is empty.</p> }
    <p><b>Total: £{{ basket.total().toFixed(2) }}</b></p>
    @if (basket.count()) { <a id="checkout" routerLink="/checkout">Go to checkout</a> }
  `,
})
export class BasketPage {
  basket = inject(Basket);
}
Also uses book.ts
export interface Book {
  id: number;
  title: string;
  author: string;
  price: number;
}
Also uses basket.ts
import { Service, signal, computed } from '@angular/core';
import { Book } from './book';

@Service()
export class Basket {
  private readonly list = signal<Book[]>([]);
  readonly items = this.list.asReadonly();
  readonly count = computed(() => this.list().length);
  readonly total = computed(() => this.list().reduce((sum, b) => sum + b.price, 0));

  add(book: Book) { this.list.update(l => [...l, book]); }
  remove(index: number) { this.list.update(l => l.filter((_, i) => i !== index)); }
  clear() { this.list.set([]); }
}
Also uses app.routes.ts
import { Routes } from '@angular/router';
import { BookList } from './book-list';

export const routes: Routes = [
  { path: '', redirectTo: 'books', pathMatch: 'full' },
  { path: 'books', component: BookList },
  { path: 'books/:id', loadComponent: () => import('./book-page').then(m => m.BookPage) },
  { path: 'basket', loadComponent: () => import('./basket-page').then(m => m.BasketPage) },
  { path: 'checkout', loadComponent: () => import('./checkout').then(m => m.Checkout) },
  { path: '**', redirectTo: 'books' },
];
Also uses app.ts
import { Component, inject } from '@angular/core';
import { RouterOutlet, RouterLink } from '@angular/router';
import { Basket } from './basket';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, RouterLink],
  template: `
    <nav class="bar">
      <a id="home" routerLink="/books"><b>Page Turners</b></a>
      <a id="cart" routerLink="/basket">Basket ({{ basket.count() }})</a>
    </nav>
    <router-outlet />
  `,
  styles: `.bar { display: flex; justify-content: space-between; margin-bottom: 8px; }`,
})
export class App {
  basket = inject(Basket);
}
Also uses book-list.ts
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { RouterLink } from '@angular/router';
import { Book } from './book';

@Component({
  selector: 'app-book-list',
  imports: [RouterLink],
  template: `
    <input (input)="q.set($any($event.target).value)" placeholder="Search books">
    @for (b of books.value(); track b.id) {
      <p><a [routerLink]="['/books', b.id]">{{ b.title }}</a> · £{{ b.price }}</p>
    } @empty { <p class="muted">No books found.</p> }
  `,
})
export class BookList {
  q = signal('');
  books = httpResource<Book[]>(() => `/api/books?q=${this.q()}`, { defaultValue: [] });
}
Also uses book-page.ts
import { Component, inject, input } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { Basket } from './basket';
import { Book } from './book';
@Component({
  selector: 'app-book-page',
  template: `
    @if (book.error()) { <p class="error">Book not found.</p> }
    @else if (book.value(); as b) {
      <h2>{{ b.title }}</h2>
      <p>by {{ b.author }} · £{{ b.price }} <button (click)="basket.add(b)">Add</button></p>
    }
  `,
})
export class BookPage {
  basket = inject(Basket);
  id = input.required<string>();
  book = httpResource<Book>(() => `/api/books/${this.id()}`);
}
Also uses checkout.ts
import { Component, inject, signal } from '@angular/core';
import { form, FormField, required, email } from '@angular/forms/signals';
import { Basket } from './basket';
@Component({
  selector: 'app-checkout', imports: [FormField], templateUrl: './checkout.html',
})
export class Checkout {
  basket = inject(Basket);
  done = signal('');
  model = signal({ name: '', email: '' });
  checkout = form(this.model, p => {
    required(p.name); required(p.email); email(p.email);
  });
  order() {
    const paid = this.basket.total().toFixed(2);
    this.done.set(`Thanks, ${this.model().name}! You paid £${paid}.`);
    this.basket.clear();
  }
}
Also uses checkout.html
<h2>Checkout</h2>
@if (done()) {
  <p class="card">{{ done() }}</p>
} @else {
  <input [formField]="checkout.name" placeholder="Name">
  <input [formField]="checkout.email" placeholder="Email">
  <p>To pay: £{{ basket.total().toFixed(2) }}</p>
  <button [disabled]="checkout().invalid()" (click)="order()">Place order</button>
}
Also uses actions.json
[{"click": "p:nth-of-type(1) a"}, {"wait": 700}, {"click": "app-book-page button"}, {"click": "#home"}, {"wait": 700}, {"click": "p:nth-of-type(4) a"}, {"wait": 700}, {"click": "app-book-page button"}, {"click": "#cart"}, {"wait": 700}, {"click": "app-basket-page button"}]
Also uses _url
/books
Also uses _bar
1

Summary

The basket page lists the items, removes them by position, and shows the total, all from the shared service. Next, checkout.

Key takeaways
  • track $index
  • basket.remove($index)
  • basket.total()
Next up: Project: Checkout Form — place the order