App owns the books, and the basket count. It passes the books down to the book list. The list passes each book down to a book card. A click on a card goes up to the list. And the list passes it up again, to App.
Book list takes a books input, and declares its own added output. For each book, it shows a card. When a card emits, the list simply emits the same book upwards.
app.tstypescript
import { Component, input, output } from '@angular/core';import { BookCard } from './book-card';import { Book } from './books';@Component({ selector: 'app-book-list', imports: [BookCard], template: ` @for (b of books(); track b.id) { <app-book-card [book]="b" (added)="added.emit($event)" /> } `,})export class BookList { books = input.required<Book[]>(); added = output<Book>();}
App passes the books in stock down to the list. When added arrives, it counts one more book in the basket. We add two books. Run it. The clicks travelled up two levels, and the count is two.
app.tstypescript
import { Component, signal } from '@angular/core';import { BookList } from './book-list';import { BOOKS } from './books';@Component({ selector: 'app-root', imports: [BookList], template: ` <h2>Basket: {{ count() }} books</h2> <app-book-list [books]="books" (added)="count.update(c => c + 1)" /> `,})export class App { books = BOOKS.filter(b => b.stock > 0); count = signal(0);}
Also uses book-list.ts
import { Component, input, output } from '@angular/core';import { BookCard } from './book-card';import { Book } from './books';@Component({ selector: 'app-book-list', imports: [BookCard], template: ` @for (b of books(); track b.id) { <app-book-card [book]="b" (added)="added.emit($event)" /> } `,})export class BookList { books = input.required<Book[]>(); added = output<Book>();}
Also uses book-card.ts
import { Component, input, output } from '@angular/core';import { Book } from './books';@Component({ selector: 'app-book-card', template: `<div class="card"><b>{{ book().title }}</b> · £{{ book().price }} <button (click)="added.emit(book())">Add</button></div>`,})export class BookCard { book = input.required<Book>(); added = output<Book>();}