In the previous lesson, an *ngFor you forgot to import left the list empty, and the else part of *ngIf needed an extra <ng-template>. Control flow blocks (blocks that decide which part of a template shows, and how many times) don't have either problem, because they're part of the template itself.
There are three blocks: @if picks whether something shows, @for repeats one part for each item of an array, and @switch picks one of several possibilities. On the menu board at Jali's Pancake Stall, "if the stock is zero, write Sold out" is @if. "Write one line for each menu item" is @for. The order-status lamp at the counter lights one of three words: being made, on the way, or delivered. That lamp is @switch.
All three have been part of the template since Angular 17, so nothing needs importing. They replace *ngIf and *ngFor from the previous lesson, and also [ngSwitch], an old directive for picking one of several possibilities. The examples here still write standalone: true, the form you still meet a lot in older code. Since Angular 19 the line is the default, in the exercise editor (Angular 22) too.
@if, @else if, @else
This example gives each menu item a stock label:
import { Component } from '@angular/core'
@Component({
selector: 'app-root',
standalone: true,
template: `
<ul>
@for (m of menu; track m.id) {
<li>
{{ m.name }}
@if (m.stock === 0) {
<b>Sold out</b>
} @else if (m.stock < 5) {
<b>{{ m.stock }} left</b>
} @else {
<b>Available</b>
}
</li>
}
</ul>
`,
})
export class App {
menu = [
{ id: 1, name: 'Chocolate Cheese Pancake', stock: 4 },
{ id: 2, name: 'Special Egg Pancake', stock: 6 },
{ id: 3, name: 'Pandan Pancake', stock: 0 },
]
}
Each part (@if, @else if, @else) is called a branch. The result for each item:
| Menu item | stock |
Branch that runs | Shows |
|---|---|---|---|
| Chocolate Cheese Pancake | 4 | @else if (m.stock < 5) |
4 left |
| Special Egg Pancake | 6 | @else |
Available |
| Pandan Pancake | 0 | @if (m.stock === 0) |
Sold out |
- The condition goes in round brackets, the branch's content in curly braces. Angular checks the branches one by one, starting from the top, and only the first branch whose condition is true is shown.
- A branch that isn't picked is not hidden: it isn't in the DOM at all.
@elsehas to sit right after the closing brace of@if. With another element in between, the compiler refuses:@else block can only be used after an @if or @else if block.@if (findMenu(); as m)stores the result offindMenu()under the namem, so the block can use that result without calculating it again.
The first exercise uses the same shape for a login button:
@if (loggedIn) {
<p>Welcome!</p>
} @else {
<p>Please log in</p>
}
<button (click)="loggedIn = !loggedIn">{{ loggedIn ? 'Logout' : 'Login' }}</button>
At first loggedIn is false, so Please log in shows. The first click makes it true, and the paragraph is replaced by Welcome!. The second click turns it back to false. The button's text is Logout while loggedIn is true, and Login while it's false.
@for and @empty
The @for block for the same menu list:
<ul>
@for (m of menu; track m.id) {
<li>{{ $index + 1 }}. {{ m.name }}</li>
} @empty {
<li>Sold out today</li>
}
</ul>
m of menu: takemenufrom the class and call each itemm.track m.idis required. Withouttrack, the template fails to compile:@for loop must have a "track" expression.@emptyis shown when the array is empty, for examplemenu = [].- Inside the block there are built-in variables:
$index(the position, starting at 0),$firstand$last(whether this is the first or the last row),$even(whether the position is even), and$count(how many items the array has). For the three menu items above, the values in Angular 18 are:
| Row | $index |
$first |
$last |
$even |
$count |
|---|---|---|---|---|---|
| Chocolate Cheese Pancake | 0 | true | false | true | 3 |
| Special Egg Pancake | 1 | false | false | false | 3 |
| Pandan Pancake | 2 | false | true | true | 3 |
track: how Angular recognises a row
When the array changes, Angular doesn't delete every <li> and make them again. It matches old rows to new items by their track value, then only moves, adds or removes what it must. So track exists to track each item's identity: to know which item is which.
For example, each <li> has an input box <input placeholder="Note" />. Then:
- You type "no spring onions" in the Chocolate Cheese Pancake row (the first row).
- The method
reverse()runsthis.menu = [...this.menu].reverse(), which reverses the order of the menu.
Before you look at the table, take a guess: if the @for is written with track $index, which pancake's row holds that note now?
track |
Order after reversing | The note "no spring onions" is in |
|---|---|---|
m.id |
Pandan Pancake, Special Egg Pancake, Chocolate Cheese Pancake | the third row, still Chocolate Cheese Pancake |
$index |
the same | the first row, now Pandan Pancake |
With track m.id, Chocolate Cheese Pancake's <li> moves down together with its note box. With track $index, Angular reads it as "row 0 is still row 0". The first <li> stays in place, and only its text changes. The note box is inside that element, so your note now sits on Pandan Pancake.
- Use a unique id (
track m.id) for a list that can be reordered, added to or removed from. track $indexis safe for a list that never changes, like the fruit list in the second exercise.- When two items share a track value, the console writes
NG0955: The provided track expression resulted in duplicated keys for a given collection.
@switch for the order status
@switch picks what to show based on the value of status:
@switch (status) {
@case ('preparing') { <p>Your pancake is being made</p> }
@case ('shipped') { <p>The courier is on the way</p> }
@case ('delivered') { <p>Your order has arrived</p> }
@default { <p>Unknown status</p> }
}
statusis compared with each@caseusing===. The match is shown. The others aren't in the DOM.@defaultis shown when nothing matches, for examplestatus = 'cancelled'.- Because the comparison uses
===,status = 1doesn't match@case ('1'): the number 1 and the text '1' are different types, so@defaultshows.
⚠️ Blocks the compiler or the checker refuses
@forwithouttrack. The whole template fails to compile. In the second exercise, write@for (item of fruits; track $index)ortrack item.- Both paragraphs outside the block. The first exercise checks there is only one
<p>in each state (logged in or not). PutWelcome!inside@ifandPlease log ininside@else. - Forgetting
@emptyin the second exercise. The data is never empty, but the code is checked for@empty. - An
@in plain text. In Angular 17 to 18,@always opens a block, so<p>Order via [email protected]</p>fails:Incomplete block "gmail". If you meant to write the @ character, you should use the "@" HTML entity instead.Angular 22 (the exercise editor) shows it as it is. In a project still on Angular 18, writebangjali@gmail.com(@is the HTML code for the @ sign).
TL;DR: The three control flow blocks (@if, @for, @switch) pick or repeat parts of a template. All three have been built into the template since Angular 17, with no import. @if (condition) { ... } @else if (...) { ... } @else { ... } shows the first branch (part of the block) whose condition is true, and the other branches aren't in the DOM. In @if, as keeps the condition's result under a name. @for (m of menu; track m.id) { ... } @empty { ... } repeats one part for each array item, with the built-in variables $index, $first, $last, $even and $count. @empty shows when the array is empty. track is required, and it tracks each item's identity: which item is which. So when the list is reversed, track m.id moves the rows, while track $index only changes their text. @switch (status) shows the @case whose value is exactly equal (===) to status, or @default when nothing matches.
⚡ @if picks one branch
Write:
@if (loggedIn) {
<p>Welcome!</p>
} @else {
<p>Please log in</p>
}
<button (click)="loggedIn = !loggedIn">Login</button>
Meaning: While loggedIn is false, Please log in shows, and each click on the button flips the value of loggedIn (false becomes true, and back). @if and @else are one branch each. Angular checks the branches one by one, starting from the top, and only the first branch whose condition is true is shown. A branch that isn't picked isn't hidden: it isn't in the DOM at all. @else has to sit right after the closing brace of @if.
In the first exercise, the page may have only one <p>, before and after a click on the button.
⚡ track tracks each item's identity
Write:
@for (m of menu; track m.id) {
<li>{{ $index + 1 }}. {{ m.name }}</li>
} @empty {
<li>Sold out today</li>
}
Guess first: the menu order is Chocolate Cheese Pancake, Special Egg Pancake, Pandan Pancake, and every row has a note box. You type in the first row, then the list is reversed. With track $index, which menu item's row holds the note?
The first row, which now holds Pandan Pancake. With track $index (the row's position, starting at 0), Angular reads it as "row 0 is still row 0": the element stays in place, and only its text changes. With track m.id, the row moves together with its note.
Meaning: @for repeats one <li> for each item of menu, and calls each item m. track is required, and it exists to track each item's identity: to know which item is which when the list changes. Use a unique id for a list that can be reordered, added to or removed from. @empty shows when the array is empty.
⚡ @switch picks one of many
Write:
@switch (status) {
@case ('preparing') { <p>Your pancake is being made</p> }
@case ('shipped') { <p>The courier is on the way</p> }
@default { <p>Unknown status</p> }
}
Meaning: @switch shows the one @case that matches the value of status, or @default when nothing matches. The values are compared with === (same value and same type), so status = 1 doesn't match @case ('1'), and @default shows.