AI Hints
Home›Angular Tutorial›@let, Class and Style Bindings and Practice: A Book List
Angular · Lesson 45 of 120

Practice: A Book List

Your turn.

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

Let's practise control flow. You'll list the books, mark the ones that are sold out, and count what's in stock.

  • List the books
  • Mark sold out
  • Count in stock

A stock list

Your turn. Pause the video, and try this. List every book, with its price. Grey out sold out books, and show sold out, or only a few left, when stock is low. And show how many books are in stock, at the top. Here is one solution. At let counts the books in stock. At for lists them, with the class binding for sold out books. And at if, with at else if, adds the stock labels. Four of five books are in stock.

✍️ Exercise: A stock list

List all books with price. [class.sold-out] when stock is 0. Show "Sold out" or "Only N left" (stock < 3). Header: "N of 5 books in stock".

Show hint

@let inStock = books.filter(b => b.stock > 0).length;

Show solution
app.tstypescript
import { Component } from '@angular/core';
import { BOOKS } from './books';

@Component({
  selector: 'app-root',
  template: `
    @let inStock = books.filter(b => b.stock > 0).length;
    <h2>{{ inStock }} of {{ books.length }} books in stock</h2>
    @for (book of books; track book.id) {
      <p [class.sold-out]="book.stock === 0">
        {{ book.title }} · £{{ book.price }}
        @if (book.stock === 0) { <b>Sold out</b> }
        @else if (book.stock < 3) { <b>Only {{ book.stock }} left</b> }
      </p>
    }
  `,
  styles: `.sold-out { color: #aaa; } b { color: crimson; }`,
})
export class App { books = BOOKS; }

What module five taught

At if, at else if, and at else show one of several blocks. At for repeats a block, with track. At empty handles empty lists. At switch picks by value. And at let, with class bindings, keeps templates tidy.

keyvalue
@if / @elseshow or hide
@for + trackrepeat
@empty, @switchspecial cases
@let, [class.x]tidy templates

Summary

You can now show, hide, and repeat parts of the page from your data. That's the end of module five. Next, how components talk to each other.

Key takeaways
  • @if
  • @for
  • @switch
Next up: Parent and Child — components that talk