The New Template Syntax
Angular has built-in control flow blocks that start with @. They replaced the older *ngIf, *ngFor and *ngSwitch directives. They are faster, need no imports and are easier to read. Old directives still work in existing code.
@if, @else if, @else
html
@if (user) {
<p>Welcome back, {{ user.name }}!</p>
} @else if (loading) {
<p>Loading...</p>
} @else {
<p>Please log in.</p>
}
<!-- save the result with 'as' -->
@if (user(); as u) {
<h2>{{ u.name }}</h2>
}
@for with track
typescript
export class TodoList {
todos = [
{ id: 1, title: 'Learn Angular', done: false },
{ id: 2, title: 'Build app', done: false },
];
}
html
<ul>
@for (todo of todos; track todo.id) {
<li [class.done]="todo.done">
{{ $index + 1 }}. {{ todo.title }}
</li>
} @empty {
<li>No todos yet.</li>
}
</ul>
track is required: track todo.id tells Angular which item is which, so it only updates the items that changed when the list changes. Use a unique id. Use track $index only for simple static lists.
| Implicit variable | Value |
$index | Position (0-based) |
$count | Number of items |
$first, $last | True for first/last |
$even, $odd | True for even/odd positions |
html
@for (item of items; track item.id; let i = $index, last = $last) {
<span>{{ i }}: {{ item.name }}@if (!last) {, }</span>
}
@switch
html
@switch (order.status) {
@case ('new') { <span class="badge new">New</span> }
@case ('shipped') { <span class="badge shipped">Shipped</span> }
@case ('delivered') { <span class="badge ok">Delivered</span> }
@default { <span>Unknown</span> }
}
@let: Template Variables
html
@let total = price * quantity;
@let name = user()?.name ?? 'Guest';
<p>{{ name }} pays {{ total }}</p>
@defer: Lazy Load Parts of the Page
@defer loads a heavy component only when needed, which makes the first page load faster.
html
@defer (on viewport) {
<app-comments [postId]="id" />
} @placeholder {
<p>Comments will appear when you scroll here</p>
} @loading (minimum 300ms) {
<p>Loading comments...</p>
} @error {
<p>Could not load comments.</p>
}
| Trigger | Loads when |
on viewport | Placeholder scrolls into view |
on idle | Browser is idle (default) |
on interaction | User clicks or presses the placeholder |
on hover | Mouse moves over it |
on timer(3s) | After a time |
when condition | An expression becomes true |
html
@defer (on interaction; prefetch on idle) {
<app-chart [data]="data()" />
} @placeholder {
<button>Show chart</button>
}
Migrating Old Code
bash
g generate @angular/core:control-flow
This schematic converts *ngIf, *ngFor and *ngSwitch to the new syntax automatically.
Conclusion
Use @if, @for (always with track), @switch and @defer for clean, fast templates. They need no imports, and the CLI can migrate old code.
Quick Summary: @if/@else, @for track + @empty, @switch, @let, @defer with triggers.