Until now, one tag in the template meant one element on the page. If Jali has three menu items, you write three <li>. Tomorrow there are ten, so you write ten. If everything sells out, the <ul> is just empty, with no message at all.
A directive solves this problem. A directive is an instruction attached to an element in a template that changes how the element is made or how it looks. Angular has a few built-in directives. Structural directives add or remove elements: *ngFor repeats, *ngIf shows on a condition. Attribute directives change the look of an element that's already there: ngClass and ngStyle. On Jali's menu board, "write one line for each menu item" is *ngFor, "write Sold out today if there's no menu" is *ngIf, and "strike through what has no stock" is ngClass.
Since Angular 17, templates have a newer built-in way to repeat and to show on a condition: the @for and @if blocks. *ngFor and *ngIf have been deprecated (marked as old, and may be removed in a later version) since Angular 20. But they're still common in existing code, and still work in the exercise editor (Angular 22). This lesson teaches the old way and the new way side by side.
Repeating: *ngFor and @for
This component shows the items of the array menu as a numbered list:
import { Component } from '@angular/core'
import { NgFor } from '@angular/common'
@Component({
selector: 'app-root',
standalone: true,
imports: [NgFor],
template: `
<ul>
<li *ngFor="let m of menu; let i = index">{{ i + 1 }}. {{ m }}</li>
</ul>
`,
})
export class App {
menu = ['Chocolate Cheese Pancake', 'Special Egg Pancake', 'Pandan Pancake']
}
Angular makes one <li> in each round:
| Round | i |
m |
The <li> created |
|---|---|---|---|
| 1 | 0 | Chocolate Cheese Pancake | 1. Chocolate Cheese Pancake |
| 2 | 1 | Special Egg Pancake | 2. Special Egg Pancake |
| 3 | 2 | Pandan Pancake | 3. Pandan Pancake |
let m of menu: takemenufrom the class, and call each itemm. Useof, notin.let i = index: the item's position, starting at 0.- The asterisk
*is a shortcut. Behind it, Angular turns the<li>into a mould (<ng-template>), then makes one copy of the<li>for each item in the array. So the element carrying*ngForis the one that repeats. NgForcomes from@angular/common, and has to be in a standalone component'simports.
The form used today, the @for block:
<ul>
@for (m of menu; track m) {
<li>{{ $index + 1 }}. {{ m }}</li>
} @empty {
<li>Sold out today</li>
}
</ul>
@forhas been part of the template since Angular 17, so there's nothing to import.track mis required. Throughtrack, Angular recognises each row when the list changes. For a list of texts that are all different, the text itself is enough to identify each row. For objects it's usuallytrack m.id. Withouttrack, the compiler refuses:@for loop must have a "track" expression.$indexis the item's position, starting at 0.@emptyshows when the array is empty.- This lesson's exercise accepts either
*ngForor@for.
Showing on a condition: *ngIf and @if
Two ways to show the text "Sold out today" when the list is empty. The second way also has an @else part:
<p *ngIf="menu.length === 0">Sold out today</p>
@if (menu.length === 0) {
<p>Sold out today</p>
} @else {
<p>{{ menu.length }} items ready to order</p>
}
*ngIfputs its element into the DOM when the condition is true, and removes it (not just hides it) when it's false. It needsNgIfinimports.@ifis built into the template and has its own@else.*ngIfneeds an<ng-template>for the else part. The details are in the next lesson, Control Flow.
Why the list can be empty
Take NgFor out of imports, and Angular doesn't recognise *ngFor. The <li> stays a mould that's never used to make copies, so the <ul> holds no <li>. The DOM is just <ul><!--container--></ul>, and the console writes:
NG0303: Can't bind to 'ngForOf' since it isn't a known property of 'li' (used in the 'App' component template).
ngForOf is the input (a value the directive receives from the template) that Angular makes out of let m of menu. *ngIf without NgIf ends the same way: Can't bind to 'ngIf' since it isn't a known property of 'p'. @for and @if don't have this problem, because neither is a directive that needs importing.
Changing the look: ngClass and ngStyle
This time each menu item is an object with a name and a stock count:
menu = [
{ name: 'Chocolate Cheese Pancake', stock: 4 },
{ name: 'Special Egg Pancake', stock: 6 },
{ name: 'Pandan Pancake', stock: 0 },
]
promoColor = 'crimson'
@for (m of menu; track m.name) {
<li [ngClass]="{ 'sold-out': m.stock === 0, 'best-seller': m.stock > 5 }">{{ m.name }}</li>
}
<p [ngStyle]="{ color: promoColor }">Tonight's promo</p>
[ngClass]takes an object. Each key (the name left of the colon) is a class name, and that class is added when the expression right of the colon istrue. Pandan Pancake gets the classsold-out, Special Egg Pancake getsbest-seller, and Chocolate Cheese Pancake gets nothing.[ngStyle]takes an object too, but each key is a style name, and its value is that style's value. Herecolorgets the value ofpromoColor, which iscrimson.[ngClass]needsNgClassinimports, and[ngStyle]needsNgStyle. For one class or one style, a plain binding is shorter and needs no import:[class.sold-out]="m.stock === 0"and[style.color]="promoColor". Angular's guide now recommends this form.
⚠️ What usually breaks the menu list
- Forgetting
imports: [NgFor]. The result is no<li>and error NG0303. Add the import, or use@for. @forwithouttrack. The template fails to compile. In the exercise, write@for (item of fruits; track item).- Typing three
<li>by hand. It looks the same, but the exercise checks that the code usesngForor@for. - A number in the text. The exercise checks that the first
<li>is exactlyAppleand the last exactlyOrange.{{ i + 1 }}. {{ item }}makes it1. Apple. In the exercise,{{ item }}is enough. - Two structural directives on one element.
<li *ngIf="..." *ngFor="...">is refused:Can't have multiple template bindings on one element. Use only one attribute prefixed with *. Use@ifinside@for.
TL;DR: A directive is an instruction attached to an element in a template. Structural directives add or remove elements: *ngFor="let m of menu; let i = index" repeats one element for each item in an array, and *ngIf="condition" places it only when the condition is true. *ngFor needs NgFor in imports, and *ngIf needs NgIf. If you forget, the list is empty and the console writes NG0303. Since Angular 17, the blocks @for (m of menu; track m) { ... } @empty { ... } and @if (...) { ... } @else { ... } do the same with no import. track is required (it identifies each row), and @empty shows when the array is empty. *ngFor and *ngIf have been deprecated (marked as old) since Angular 20. Attribute directives change the look: [ngClass]="{ 'sold-out': m.stock === 0 }" adds the class sold-out when m.stock === 0 is true, and [ngStyle] sets styles. For one class or style, [class.sold-out] and [style.color] are shorter.
⚡ @for repeats one element
Write:
<ul>
@for (m of menu; track m) {
<li>{{ m }}</li>
} @empty {
<li>Sold out today</li>
}
</ul>
Guess first: track m is required in @for. What happens if it is deleted?
The template fails to compile: @for loop must have a "track" expression. With track, Angular recognises each row when the list changes.
Meaning: The @for block makes one <li> for each item of the array menu, and calls that item m. @empty shows when the array is empty. @for has been part of the template since Angular 17, so there's nothing to import.
⚡ *ngFor needs imports
Write:
imports: [NgFor],
template: `<li *ngFor="let m of menu; let i = index">{{ i + 1 }}. {{ m }}</li>`,
Guess first: NgFor is taken out of imports. How many <li> appear?
None. Without NgFor, Angular doesn't recognise *ngFor. The <li> becomes a mould that's never used to make copies, and the console writes error NG0303.
Meaning: *ngFor is the old way to repeat, and it needs NgFor in imports. let m of menu gives each item of menu the name m, and let i = index is its position, starting at 0. *ngFor has been deprecated (marked as old) since Angular 20, and so has *ngIf, the old way to show an element on a condition. Both are still common in older code. The exercise accepts either *ngFor or @for.
In the exercise, the first <li> must be exactly Apple and the last Orange, so show just {{ item }} with no number.
⚡ ngClass adds classes
Write:
<li [ngClass]="{ 'sold-out': m.stock === 0, 'best-seller': m.stock > 5 }">{{ m.name }}</li>
Meaning: [ngClass] takes an object. Each key (the name left of the colon) is a class name, and that class is added when the expression right of the colon is true. Here an item with stock 0 gets the class sold-out, and an item with more than 5 in stock gets best-seller. For a single class, [class.sold-out]="m.stock === 0" is shorter and needs no import.