← Learning Hub
Beginner

Conditions and Lists (@if, @for)

Angular templates have built-in blocks to show things conditionally and to repeat things:

Templates often need logic: show the cart only if it has items, show a loading message while data arrives, repeat a card for every product. Angular's control flow blocks (@if, @for, @switch) look like JavaScript and make this easy to read. They replaced the older *ngIf and *ngFor directives you may see in older code.

  • @if (condition) { ... } @else { ... } shows a part only when the condition is true.
  • @for (item of items; track item.id) { ... } repeats a part for each item.
  • @empty { ... } inside @for shows something when the list is empty.
Example
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-product-list',
  template: `
    @for (p of products(); track p.id) {
      <div>
        {{ p.name }} - Rs {{ p.price }}
        @if (p.inStock) {
          <b>In stock</b>
        } @else {
          <i>Out of stock</i>
        }
      </div>
    } @empty {
      <p>No products found.</p>
    }
  `,
})
export class ProductList {
  products = signal([
    { id: 1, name: 'Shoes', price: 1499, inStock: true },
    { id: 2, name: 'Watch', price: 2999, inStock: false },
  ]);
}
track tells Angular how to recognise each item (usually its id), so lists update quickly and correctly.
Key points
  • @if / @else show content conditionally.
  • @for repeats content; track is required.
  • @empty handles an empty list.

📝 Test yourself

1. Which block repeats part of a template for each item?
2. What does @empty show?
3. Fill in the word that tells @for how to recognise items:
@for (p of products(); p.id) { }