AI Hints
Home›Angular Tutorial›track, @empty and @switch
Angular · Lesson 40 of 120

track

Telling items apart.

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

When a list changes, Angular doesn't rebuild every item. It moves, adds, and removes only what it must. To do that, it needs to know which item is which.

  • Lists change
  • Only change what's needed
  • Which item is which?

What track does

Track gives each item an identity, usually its id. When the list changes, Angular matches items by that identity. Items that only moved are moved, not rebuilt. That keeps big lists fast, and keeps things like focus, and typed text, in place.

keyvalue
track book.ideach item's identity
List changesmatched by identity
Moved itemsmoved, not rebuilt
Resultfast, and nothing lost

Sorting the list

Books is a signal, holding the five books. Cheapest first replaces it with a sorted copy. Because we track by id, Angular simply moves the existing rows into the new order. We click the button. Run it. The books are now sorted, from the cheapest.

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

@Component({
  selector: 'app-root',
  template: `
    <button (click)="cheapestFirst()">Cheapest first</button>
    @for (book of books(); track book.id) {
      <p>{{ book.title }} · £{{ book.price }}</p>
    }
  `,
})
export class App {
  books = signal(BOOKS);

  cheapestFirst() {
    this.books.update(list => [...list].sort((a, b) => a.price - b.price));
  }
}
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 },
];
Also uses actions.json
[{"click": "button"}]

What to track

Track a unique id whenever the items have one. For a simple list of strings, track the item itself. Dollar index is only safe when the list never changes order. Never track something that can repeat.

TrackWhen
book.iditems with an id (best)
titlea list of unique strings
$indexlists that never reorder
Nevervalues that can repeat

Summary

Track gives each item an identity, so Angular can move items, instead of rebuilding them. Track the id. Next, at empty.

Key takeaways
  • track book.id
  • Moved, not rebuilt
  • Avoid $index
Next up: @empty — when the list is empty