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

Class and Style Bindings

Change the look.

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

Sold out books should look different. Greyed out, maybe crossed out. Angular can switch CSS classes, and styles, based on data.

  • Sold out looks different
  • Switch classes
  • Based on data

Class and style bindings

Class dot sold out, in square brackets, adds the class when the expression is true, and removes it when false. Style dot font weight sets one style, from an expression. Both update when the data changes.

keyvalue
[class.sold-out]="..."add or remove a class
[style.font-weight]="..."set one style
[style.width.px]="w"with a unit
Updateswhen data changes

Sold out and low stock

For each book, the sold out class is added, when its stock is zero. The style binding makes the text bold, when stock is below three. And the sold out class greys the text, and crosses it out. Run it. The Hobbit is crossed out. Circe, and Persuasion, are bold, because stock is low.

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

@Component({
  selector: 'app-root',
  template: `
    @for (book of books; track book.id) {
      <p [class.sold-out]="book.stock === 0"
         [style.font-weight]="book.stock < 3 ? 'bold' : 'normal'">
        {{ book.title }} ({{ book.stock }} left)
      </p>
    }
  `,
  styles: `.sold-out { color: #aaa; text-decoration: line-through; }`,
})
export class App {
  books = BOOKS;
}
Also uses books.ts
export interface Book {
  id: number;
  title: string;
  author: string;
  price: number;
  stock: number;
}

export const BOOKS: Book[] = [
  { id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99, stock: 4 },
  { id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien', price: 8.99, stock: 0 },
  { id: 3, title: 'Circe', author: 'Madeline Miller', price: 10.99, stock: 2 },
  { id: 4, title: 'Emma', author: 'Jane Austen', price: 6.99, stock: 7 },
  { id: 5, title: 'Persuasion', author: 'Jane Austen', price: 7.49, stock: 1 },
];

Summary

Class dot name adds a class when true, and style dot property sets a style, from your data. Next, some practice.

Key takeaways
  • [class.sold-out]
  • [style.font-weight]
  • Data-driven looks
Next up: Practice: A Book List — your turn