Blog

Part 4 · Control Flow in Angular: @if, @for with track, @switch and @let

Show, hide and repeat parts of a template with @if, @for, @switch and @let. Why @for needs track, what goes wrong with track $index, and a filterable todo list.

So far every template has shown the same elements every time. Real pages don’t. A message appears only when the cart is empty. A list has one row per item, and the rows come and go. Angular’s templates have control flow blocks for this: @if, @for, @switch and @let.

This part covers all four, with most of the time on @for and its track expression, because that’s where the real bugs hide. In Part 3 we kept changing values in signals. Here the template decides what to show from those signals. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

Paste this into src/app/app.ts. It shows a shopping list with a checkbox on each row, and a button that removes the first item.

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface Item {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  template: `
    <ul>
      @for (item of items(); track $index) {
        <li>
          <label><input type="checkbox" #box (change)="onTick()" /> {{ item.name }}</label>
          {{ box.checked ? '(ticked)' : '' }}
        </li>
      }
    </ul>
    <button (click)="removeFirst()">Remove first</button>
  `,
})
export class App {
  protected readonly items = signal<Item[]>([
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Bread' },
    { id: 3, name: 'Milk' },
  ]);

  protected onTick() {}

  protected removeFirst() {
    this.items.update((list) => list.slice(1));
  }
}

#box is a template reference variable from Part 2: it names the checkbox, so box.checked reads whether it’s ticked. onTick is empty on purpose. It’s there so the checkbox has a (change) listener: after an event in the template, Angular redraws (Part 3), so the “(ticked)” text keeps up with the box. list.slice(1) makes a new list with everything except the first item.

Tick Apple. The page shows:

Apple (ticked)
Bread
Milk
Remove first

Before you read on, guess. You click Remove first, and Apple goes away. Which row is ticked now?

Here’s what happens. After Remove first, the page shows:

Bread (ticked)
Milk
Remove first

Bread is ticked, and you never touched it. Nothing in items says anything about ticks, so the tick must live somewhere else. By the end of the @for section you’ll know where, and the one-word fix.

@if, @else if and @else

@if shows a piece of template only while a condition is true:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <p>Score: {{ score() }}</p>
    @if (score() >= 90) {
      <p>Excellent</p>
    } @else if (score() >= 50) {
      <p>Pass</p>
    } @else {
      <p>Try again</p>
    }
    <button (click)="score.set(40)">40</button>
    <button (click)="score.set(75)">75</button>
    <button (click)="score.set(95)">95</button>
  `,
})
export class App {
  protected readonly score = signal(40);
}

When the page loads, it shows:

Score: 40
Try again
407595

Click 95, and it shows:

Score: 95
Excellent
407595

The three buttons run together into 407595 because buttons sit on one line, and the page text joins them.

Angular checks the conditions from the top and shows the first block whose condition is true. @else if and @else are optional. The condition is any template expression, and because it reads score(), a signal, the blocks switch when the score changes.

@if doesn’t hide anything. When the condition is false, the elements in that block aren’t on the page at all. When it becomes true, Angular creates them. When it turns false again, Angular destroys them, along with anything they held, like text typed into an input. Open the Elements tab in your browser’s developer tools and click the buttons. You’ll see the <p> being swapped, not hidden.

@if with as: name the value you tested

A common case is a value that might be missing. Here user holds either a user or null:

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface User {
  name: string;
  email: string;
}

@Component({
  selector: 'app-root',
  template: `
    @if (user(); as u) {
      <p>Signed in as {{ u.name }} ({{ u.email }})</p>
    } @else {
      <p>Nobody is signed in.</p>
    }
    <button (click)="signIn()">Sign in</button>
    <button (click)="user.set(null)">Sign out</button>
  `,
})
export class App {
  protected readonly user = signal<User | null>(null);

  protected signIn() {
    this.user.set({ name: 'Ana', email: 'ana@example.com' });
  }
}

User | null is a TypeScript union type: the value is a User or it’s null. Click Sign in. The page shows:

Signed in as Ana (ana@example.com)
Sign inSign out

@if (user(); as u) tests the value and gives it a name, u, inside the block. Inside, TypeScript knows u is a User, not null, because the block only runs when the test passed.

Why not just write user().name inside the block? Because each user() is a separate call, and TypeScript doesn’t assume two calls return the same thing. So this doesn’t build:

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface User {
  name: string;
  email: string;
}

@Component({
  selector: 'app-root',
  template: `
    @if (user()) {
      <p>Signed in as {{ user().name }}</p>
    }
  `,
})
export class App {
  protected readonly user = signal<User | null>(null);
}
✘ [ERROR] TS2531: Object is possibly 'null'. [plugin angular-compiler]

as u reads the signal once and keeps the result. That’s the fix.

@for: one block per item

@for repeats a block for each item in a list. Part 3 used it already. Here’s the full shape:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <ul>
      @for (name of names(); track name) {
        <li>
          {{ $index + 1 }} of {{ $count }}: {{ name }} {{ $first ? '(first)' : '' }}
          {{ $last ? '(last)' : '' }}
          {{ $even ? 'even' : 'odd' }}
        </li>
      } @empty {
        <li>No names yet.</li>
      }
    </ul>
    <button (click)="names.set([])">Clear</button>
  `,
})
export class App {
  protected readonly names = signal(['Ana', 'Ben', 'Chen']);
}

The page shows:

1 of 3: Ana (first) even
2 of 3: Ben odd
3 of 3: Chen (last) even
Clear

Click Clear, and it shows:

No names yet.
Clear

Piece by piece:

  • name of names() gives each item a name inside the block. names() is the signal’s value, so when the list changes, the rows change.
  • track name tells Angular how to tell one item from another. It’s required. We’ll come back to it in a moment.
  • Inside the block, Angular gives you some contextual variables: $index is the position, starting at 0. $count is how many items there are. $first and $last are true on the first and last row. $even and $odd go by $index, so the first row, at index 0, is even.
  • @empty is shown when the list has no items. It’s optional.

You can give a contextual variable another name with let: @for (name of names(); track name; let i = $index). You need that when one @for sits inside another, because the inner loop’s $index hides the outer one. Exercise 2 does this.

Why @for needs track

Back to the mystery from the start. When items changes, Angular doesn’t throw away every row and build new ones. That would be slow, and it would lose everything the rows held. Instead, it compares the old list with the new one and works out what to change: which rows to keep, which to move, which to create and which to destroy.

To compare them, it needs to know which old item is which new item. That’s what track says. For each item, Angular works out the track value. Items with the same track value are the same item, so they keep the same DOM row.

In the first example, we tracked by $index, the position. Before the removal, Apple was at position 0. After it, Bread is at position 0. Same track value, so Angular decided “position 0 is the same item as before” and kept the row. It only changed the name in it from Apple to Bread. The checkbox in that row is the same element, so it’s still ticked. Position 2 no longer exists, so Angular destroyed the last row.

A ticked checkbox, text in an input, focus, a scroll position, a running CSS animation: these live in the DOM element, not in your signal. With the wrong track, they stay with the position instead of with the item.

The fix is one word. Track by something that belongs to the item and never changes, its id:

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface Item {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  template: `
    <ul>
      @for (item of items(); track item.id) {
        <li>
          <label><input type="checkbox" #box (change)="onTick()" /> {{ item.name }}</label>
          {{ box.checked ? '(ticked)' : '' }}
        </li>
      }
    </ul>
    <button (click)="removeFirst()">Remove first</button>
  `,
})
export class App {
  protected readonly items = signal<Item[]>([
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Bread' },
    { id: 3, name: 'Milk' },
  ]);

  protected onTick() {}

  protected removeFirst() {
    this.items.update((list) => list.slice(1));
  }
}

Tick Apple and click Remove first. Now the page shows:

Bread
Milk
Remove first

Apple’s row went away with Apple. Bread and Milk kept their own rows, unticked.

This animation shows both versions side by side. The labels row 1, row 2 and row 3 name the DOM elements, so you can follow each one.

items() signal track item.id track $index Apple Bread Milk Bread Milk Apple removed ✓ Apple row 1 Bread row 2 Milk row 3 Bread row 2 Milk row 3 ✓ Apple row 1 row 1 destroyed ✓ Apple row 1 Bread row 2 Milk row 3 ✓ Bread row 1 Milk row 2 Milk row 3 row 3 destroyed Apple is ticked, in row 1 items() changed; the rows haven't been updated yet track item.id: Bread and Milk unticked, as they should be track $index: Bread looks ticked, but you never ticked it Each item gets a DOM row. The tick lives in the row's checkbox Remove first: items() is now Bread, Milk track item.id: row 1 is removed; rows 2 and 3 stay, now at the top track $index: row 1 is reused for Bread and keeps its tick

Angular matches old and new items by their track value. The rows, and what they hold, follow that match.

Here are those steps in words, in case the animation doesn’t play for you:

  1. items() holds Apple, Bread and Milk. Each has a DOM row, labelled here row 1, row 2 and row 3. You ticked the checkbox in row 1, Apple’s row. The tick is in the checkbox element, not in items().
  2. Remove first sets items() to Bread and Milk. Angular now has to match the new list to the rows it already has.
  3. With track item.id, Bread (id 2) is matched to row 2 and Milk (id 3) to row 3. Apple’s id is gone, so row 1 is removed, tick and all. Rows 2 and 3 stay where they are in the DOM; with row 1 gone, they shift up on the screen. Nothing on the page is ticked, which is right.
  4. With track $index, position 0 is matched to row 1 and position 1 to row 2. Row 1 keeps its ticked checkbox and only its text changes to Bread. Position 2 is gone, so row 3 is destroyed. Bread now looks ticked, which is wrong.

What to track

  • An id (track item.id): the right choice for data with ids, which is most data from a server. The row follows the item through removals, inserts and reorders.
  • The item itself (track item): fine for a list of strings or numbers that don’t repeat, like the names above. For objects, it compares references, the same way a signal does (Part 3). If you replace an object with an updated copy, { ...todo, done: true }, that’s a new reference, so Angular destroys the old row and creates a new one. Exercise 3 shows what that costs.
  • The position (track $index): only for lists that never reorder and only change at the end, and whose rows hold no state of their own. Part 3 used it for a list of plain strings that only grew at the end.

If two items have the same track value, Angular can’t tell them apart. It checks for that when it compares an old list with a new one, so nothing is logged on the first render. Here two items share id 1:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    @for (item of items(); track item.id) {
      <p>{{ item.name }}</p>
    }
    <button (click)="addMilk()">Add milk</button>
  `,
})
export class App {
  protected readonly items = signal([
    { id: 1, name: 'Apple' },
    { id: 1, name: 'Bread' },
  ]);

  protected addMilk() {
    this.items.update((list) => [...list, { id: 2, name: 'Milk' }]);
  }
}

The page loads quietly. Click Add milk, and the page shows:

Apple
Bread
Milk
Add milk

and the console gets a warning (shown while you develop, not in a production build):

NG0955: The provided track expression resulted in duplicated keys for a given collection.

A list that never changes never warns, so make sure your ids really are unique.

@switch: pick one of several blocks

When one value picks between several blocks, @switch reads better than a chain of @else if:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    @switch (size()) {
      @case ('small') {
        <p>Fits in a pocket</p>
      }
      @case ('medium')
      @case ('large') {
        <p>Needs a bag</p>
      }
      @default {
        <p>Unknown size</p>
      }
    }
    <button (click)="size.set('small')">Small</button>
    <button (click)="size.set('large')">Large</button>
    <button (click)="size.set('huge')">Huge</button>
  `,
})
export class App {
  protected readonly size = signal('small');
}

Click Large. The page shows:

Needs a bag
SmallLargeHuge

Click Huge, and it shows:

Unknown size
SmallLargeHuge

Angular compares the @switch value with each @case value using ===, and shows the first match. If nothing matches, it shows @default, if there is one. A @case with no body, like @case ('medium') here, shares the body of the next case: medium and large both show “Needs a bag”. A body never runs on into the next case’s body, so there’s no break to forget.

Let the compiler check every case

Often the value can only be one of a few strings. In TypeScript, you write that as a union of string types: type Size = 'small' | 'medium' | 'large'. Then you can ask the compiler to check that the @switch handles every one, with @default never;:

// src/app/app.ts
import { Component, signal } from '@angular/core';

type Size = 'small' | 'medium' | 'large';

@Component({
  selector: 'app-root',
  template: `
    @let current = size();
    @switch (current) {
      @case ('small') {
        <p>Fits in a pocket</p>
      }
      @case ('medium')
      @case ('large') {
        <p>Needs a bag</p>
      }
      @default never;
    }
    <button (click)="size.set('medium')">Medium</button>
  `,
})
export class App {
  protected readonly size = signal<Size>('small');
}

Click Medium. The page shows:

Needs a bag
Medium

@default never; means “no value should ever get here”. If a value of the type isn’t handled by a @case, the build fails. The worked example below shows that error.

Notice the @let current = size(); line. It reads the signal once and switches on the result. That isn’t just style. If you switch on size() directly, the build fails even when every case is there, because TypeScript can’t assume two calls to size() return the same value. It’s the same reason @if needed as above. The next section explains @let.

@let: a name for a value in the template

@let declares a variable in the template:

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface Order {
  id: number;
  items: string[];
}

@Component({
  selector: 'app-root',
  template: `
    @let o = order();
    @let count = o.items.length;
    <p>Order {{ o.id }}: {{ count }} {{ count === 1 ? 'item' : 'items' }}</p>
    @if (count > 1) {
      @let rest = count - 1;
      <p>{{ o.items[0] }} and {{ rest }} more</p>
    }
    <button (click)="addTea()">Add tea</button>
  `,
})
export class App {
  protected readonly order = signal<Order>({ id: 7, items: ['Coffee'] });

  protected addTea() {
    this.order.update((o) => ({ ...o, items: [...o.items, 'Tea'] }));
  }
}

The page shows:

Order 7: 1 item
Add tea

Click Add tea, and it shows:

Order 7: 2 items
Coffee and 1 more
Add tea

What @let does and doesn’t do:

  • It reads the expression each time the template is drawn. count followed the order when it changed. It isn’t a snapshot from the first render.
  • It saves repeating a long expression, and it reads a signal once per render, so every use sees the same value.
  • It’s visible from its line to the end of the block it’s in, including blocks inside. rest exists only inside the @if. Using count above its @let line fails the build with NG8016, Cannot read @let declaration 'count' before it has been defined.
  • You can’t assign to it. (click)="count = 5" fails the build. The output first shows an error about generated code, Cannot assign to "count_r2" because it is a constant (the name may differ), and then the useful one, NG8015, Cannot assign to @let declaration 'count'. To change a value, change the signal it comes from.
  • An unused @let gets an NG8112 warning, so delete it rather than leave it.

Worked example: a filterable todo list

Now the pieces together. A todo list with All, Active and Done filters, a heading for each filter, a message when a filter shows nothing, and a count of what’s left.

// src/app/app.ts
import { Component, computed, signal } from '@angular/core';

interface Todo {
  id: number;
  text: string;
  done: boolean;
}

type Filter = 'all' | 'active' | 'done';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="filter.set('all')">All</button>
    <button (click)="filter.set('active')">Active</button>
    <button (click)="filter.set('done')">Done</button>
    @let f = filter();
    @switch (f) {
      @case ('all') {
        <h2>Everything</h2>
      }
      @case ('active') {
        <h2>Still to do</h2>
      }
      @case ('done') {
        <h2>Finished</h2>
      }
      @default never;
    }
    <ul>
      @for (todo of visible(); track todo.id) {
        <li>
          <label>
            <input type="checkbox" [checked]="todo.done" (change)="toggle(todo.id)" />
            {{ todo.text }}
          </label>
        </li>
      } @empty {
        <li>Nothing here.</li>
      }
    </ul>
    @let left = remaining();
    <p>{{ left }} {{ left === 1 ? 'task' : 'tasks' }} left</p>
  `,
})
export class App {
  protected readonly todos = signal<Todo[]>([
    { id: 1, text: 'Buy milk', done: false },
    { id: 2, text: 'Call Ana', done: true },
    { id: 3, text: 'Write tests', done: false },
  ]);
  protected readonly filter = signal<Filter>('all');
  protected readonly visible = computed(() => {
    const f = this.filter();
    return this.todos().filter((t) => f === 'all' || (f === 'done') === t.done);
  });
  protected readonly remaining = computed(() => this.todos().filter((t) => !t.done).length);

  protected toggle(id: number) {
    this.todos.update((list) => list.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
  }
}

Some things to notice:

  • All the state is in two signals: todos and filter. What’s shown is computed from them. The template only decides how to draw it.
  • visible keeps a todo when the filter is 'all', or when “the filter is done” matches “the todo is done”. For Active, that keeps the todos that aren’t done.
  • This time the checkbox is bound: [checked]="todo.done" draws it from the data, and (change) updates the data. The tick is in the signal, not only in the DOM, so it can’t end up on the wrong row.
  • toggle makes a new todo object with { ...t, done: !t.done }, as Part 3 taught. Because we track by todo.id, Angular keeps the row and just updates the checkbox. With track todo, the new object would get a brand new row.

When the page loads, it shows:

AllActiveDone
Everything
Buy milk
Call Ana
Write tests
2 tasks left

Click Done. The page shows:

AllActiveDone
Finished
Call Ana
2 tasks left

Now untick Call Ana. It isn’t done any more, so it leaves the Done list, and @empty takes its place:

AllActiveDone
Finished
Nothing here.
3 tasks left

Worked example: two build errors

Control flow blocks are checked when you build, like the rest of the template. Here are two errors you’ll meet.

First, someone writes a @for without track, as you might in a hurry:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <ul>
      @for (name of names()) {
        <li>{{ name }}</li>
      }
    </ul>
  `,
})
export class App {
  protected readonly names = signal(['Ana', 'Ben']);
}

ng serve stops with:

✘ [ERROR] NG5002: @for loop must have a "track" expression [plugin angular-compiler]
      8 │       @for (name of names()) {
  • NG5002 is the code Angular uses for template syntax errors, the kind found while reading the template, before any types are checked.
  • The message says exactly what’s missing. Angular made track required so that every list makes a choice about it. Here the names are unique strings, so track name is right.
  • The line below shows the line from your file with the @for underlined. (In the real output, the file path, src/app/app.ts:8:6 with your project’s folder in front, sits between the error line and that code line.)

The second error is one you want. The todo list’s Filter type gets a new value, 'starred', but nobody adds a heading for it:

// src/app/app.ts
import { Component, signal } from '@angular/core';

type Filter = 'all' | 'active' | 'done' | 'starred';

@Component({
  selector: 'app-root',
  template: `
    @let f = filter();
    @switch (f) {
      @case ('all') {
        <h2>Everything</h2>
      }
      @case ('active') {
        <h2>Still to do</h2>
      }
      @case ('done') {
        <h2>Finished</h2>
      }
      @default never;
    }
  `,
})
export class App {
  protected readonly filter = signal<Filter>('all');
}
✘ [ERROR] TS2322: Type '"starred"' is not assignable to type 'never'. [plugin angular-compiler]

Read it this way. never is TypeScript’s type for “no value at all”. @default never; asks the compiler to prove that after all the cases, nothing is left. It found one value that’s left, "starred", and names it. Add @case ('starred') { <h2>Starred</h2> } and it builds. Without @default never;, this would build, and the starred filter would show no heading. You’d find out from a user.

In older code

Before Angular 17, templates used structural directives for this: *ngIf="user; else noUser", *ngFor="let item of items; trackBy: trackById" and [ngSwitch] with *ngSwitchCase. They needed NgIf, NgFor and NgSwitch from @angular/common in the component’s imports. Those directives still work in Angular 22, but they’ve been marked deprecated since Angular 20, so expect them to be removed in a later version. In *ngFor, tracking was optional and done by a trackBy function in the class, so many lists had none. The @ blocks replace all of them, need no imports, and make track required. Angular has a migration that converts old templates: ng generate @angular/core:control-flow.

Best practices

  • Track by a stable id. track item.id keeps each row with its item through removals and reorders. It replaces track $index, which ties rows to positions, and track item, which recreates rows whenever an object is replaced with a copy.
  • Keep state in signals, not in the DOM. Bind checkboxes and inputs to data, as the todo list does, instead of leaving the tick in an unbound element. Then even a wrong track can’t move it to another item.
  • Name what @if tests with as. @if (user(); as u) reads the signal once and gives TypeScript a value it knows isn’t null. It replaces user()!.name and repeated calls.
  • Use @default never; on a @switch over a union type. The build then fails when someone adds a new value and forgets a case. Switch on a @let variable, not a direct signal call.
  • Put logic in computed, not in the template. Filtering, sorting and counting go in a computed like visible. The template then reads one name, and @let is for short aliases, not for working things out.

Tips and traps

  • Forgetting track. The build fails with NG5002, @for loop must have a "track" expression. Add track item.id, or track item for unique strings or numbers.
  • track $index on a list that changes. Nothing errors. A tick, typed text or focus shows up on the wrong row after a removal or reorder. Track by an id.
  • A signal without () in @if. @if (loggedIn) gets the NG8109 warning from Part 3, and with the strict settings of a new project the build also fails with TS2774, This condition will always return true since this function is always defined. Add the ().
  • @switch (size()) with @default never;. The build fails with TS2322 even when every case is there, because each size() is a separate call. Write @let current = size(); and switch on current.
  • Expecting @if to keep what’s inside. When the condition turns false, the elements are destroyed, with any typed text. Keep that text in a signal if it must survive.
  • Two items with the same track value. Angular can’t tell them apart. The first change to the list logs NG0955 in the console; the first render logs nothing. Make sure the id really is unique.

track tells Angular which item each row belongs to, and the row keeps everything it holds only if that answer is right.

Exercises

Exercise 1. This page is meant to show a product’s price when one is picked. It doesn’t build. Read the error, then fix it without using !.

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface Product {
  name: string;
  price: number;
}

@Component({
  selector: 'app-root',
  template: `
    @if (picked()) {
      <p>{{ picked().name }} costs {{ picked().price }}</p>
    } @else {
      <p>Pick a product.</p>
    }
    <button (click)="picked.set({ name: 'Tea', price: 3 })">Tea</button>
  `,
})
export class App {
  protected readonly picked = signal<Product | null>(null);
}

Exercise 2. Write a component with a signal rows holding [['A', 'B'], ['C', 'D']], and show it as seats: one line per row, each seat labelled with its row number and seat number, both starting at 1. The page should show Row 1: 1.1 A 1.2 B and Row 2: 2.1 C 2.2 D. Hint: you need the outer loop’s $index inside the inner loop.

Exercise 3. In this page, the rows track by the item itself. Refresh replaces each item with a copy, the way new data from a server would arrive. Tick Apple, then click Refresh. Is Apple still ticked? Why? Change one word so it is.

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface Item {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  template: `
    <ul>
      @for (item of items(); track item) {
        <li>
          <label><input type="checkbox" #box (change)="onTick()" /> {{ item.name }}</label>
          {{ box.checked ? '(ticked)' : '' }}
        </li>
      }
    </ul>
    <button (click)="refresh()">Refresh</button>
  `,
})
export class App {
  protected readonly items = signal<Item[]>([
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Bread' },
  ]);

  protected onTick() {}

  protected refresh() {
    this.items.update((list) => list.map((item) => ({ ...item })));
  }
}
Answers

1. The build fails with TS2531: Object is possibly 'null', pointing at picked().name. TypeScript doesn’t assume the second call to picked() returns the same thing the @if tested. Name the tested value with as:

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface Product {
  name: string;
  price: number;
}

@Component({
  selector: 'app-root',
  template: `
    @if (picked(); as p) {
      <p>{{ p.name }} costs {{ p.price }}</p>
    } @else {
      <p>Pick a product.</p>
    }
    <button (click)="picked.set({ name: 'Tea', price: 3 })">Tea</button>
  `,
})
export class App {
  protected readonly picked = signal<Product | null>(null);
}

Click Tea. The page shows:

Tea costs 3
Tea

2. Give the outer $index its own name with let, so the inner loop can still see it:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    @for (row of rows(); track $index; let r = $index) {
      <p>
        Row {{ r + 1 }}:
        @for (seat of row; track seat) {
          {{ r + 1 }}.{{ $index + 1 }} {{ seat }}
        }
      </p>
    }
  `,
})
export class App {
  protected readonly rows = signal([
    ['A', 'B'],
    ['C', 'D'],
  ]);
}

The page shows:

Row 1: 1.1 A 1.2 B
Row 2: 2.1 C 2.2 D

track $index is fine for the outer loop here: the rows never move, and a row holds no state of its own.

3. No. The tick is gone. track item compares object references, and refresh made a new object for every item. To Angular, every old item left and new ones arrived, so it destroyed every row and created new ones, with fresh checkboxes. Angular notices this while you develop and logs a warning in the console:

NG0956: The configured tracking expression (track by identity) caused re-creation of the entire collection of size 2.

Track by the id, which the copies share:

// src/app/app.ts
import { Component, signal } from '@angular/core';

interface Item {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  template: `
    <ul>
      @for (item of items(); track item.id) {
        <li>
          <label><input type="checkbox" #box (change)="onTick()" /> {{ item.name }}</label>
          {{ box.checked ? '(ticked)' : '' }}
        </li>
      }
    </ul>
    <button (click)="refresh()">Refresh</button>
  `,
})
export class App {
  protected readonly items = signal<Item[]>([
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Bread' },
  ]);

  protected onTick() {}

  protected refresh() {
    this.items.update((list) => list.map((item) => ({ ...item })));
  }
}

Tick Apple and click Refresh. The page shows:

Apple (ticked)
Bread
Refresh

What’s next

Everything so far has lived in one App component. In Part 5, we’ll split a page into child components and pass data down to them with input().

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.