Skip to main content

Conditionals

Property binding and Event binding are powerful mechanisms, but you will often need to branch between multiple options.

@ifโ€‹

The @if control flow allows you to conditionally display a block of the view based on the truthiness of an expression.

@if (name) {
<h1>Hello, {{ name }}!</h1>
}

You can also use @else to render a fallback:

@if (name) {
<h1>Hello, {{ name }}!</h1>
} @else {
<h1>Hello, guest!</h1>
<a href="/signin">Sign In</a>
}

@switchโ€‹

When you need to branch between multiple options, @switch gives you a clean way to avoid deep @if nesting:

@switch (recipe.difficulty) {
@case ('easy') {
<span>๐ŸŸข Easy โ€” great for beginners</span>
}
@case ('medium') {
<span>๐ŸŸ  Medium โ€” some prep involved</span>
}
@case ('hard') {
<span>๐Ÿ”ด Hard โ€” experienced cooks</span>
}
@default {
<span>โ“ Unknown difficulty</span>
}
}
info

The new control flow syntax (e.g. @if/else, @switch/case, etc...) are a drop-in replacement for the old microsyntax (i.e. *ngIf, *ngSwitch, etc...).

tip

@switch is type-safe.

@switch (recipe.difficulty) {
...
@case (42) { // โŒ NG8: Type '42' is not comparable to type 'Difficulty'.
<span>๐Ÿ”‘ Secret recipe</span>
}
...
}
Pragmatic Angular Testing
๐Ÿ‘จ๐Ÿปโ€๐Ÿณ Let's cook some tests โ†’

๐Ÿ’ฐ 80โ‚ฌ ยท 170โ‚ฌ ยท Lifetime access

Learn how to write reliable tests that survive upgrades and refactorings.