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

Project: The Book Page

One book.

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

Each book has its own page, at books slash id. It loads that one book, and lets the customer add it to the basket.

  • A page per book
  • Load one book
  • Add to basket

The book page

The id input comes from the route parameter. The HTTP resource loads that book, and reloads if the id changes. The button adds the book to the shared basket. We click Circe, on the list, and add it. Run it. The address is books slash three, and the header now says basket one.

book-page.tstypescript
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()}`);
}
Output
API GET /api/books?q= → 200
API GET /api/books/3 → 200
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 basket-page.ts
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 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(3) a"}, {"wait": 700}, {"click": "app-book-page button"}, {"wait": 300}]
Also uses _url
/books
Also uses _bar
1
Also uses _apilog
1

A missing book

What if the book doesn't exist? The server answers four oh four, and the resource's error signal is set. We open books slash ninety nine. Run it. The page says book not found, instead of breaking.

book-page.tstypescript
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()}`);
}
Output
API GET /api/books/99 → 404
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 basket-page.ts
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 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 _url
/books/99
Also uses _bar
1
Also uses _apilog
1

Summary

The book page reads its id from the route, loads the book with HTTP resource, and adds it to the shared basket. Next, the basket page.

Key takeaways
  • id = input.required()
  • httpResource
  • basket.add(b)
Next up: Project: The Basket — review the order