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
tip
@switch
is type-safe.
@switch (recipe.difficulty) {
...
@case (42) { // โ NG8: Type '42' is not comparable to type 'Difficulty'.
<span>๐ Secret recipe</span>
}
...
}