Sub topic 3
Handling alternatives with @else if and @else
This chapter assumes you know TypeScript basics, how Angular components and templates fit together, and how to use interpolation and event or property bindings. Familiarity with signals helps, because the examples use them. You should also have seen a basic @if block, which the previous chapter covered.
Why alternatives matter
A single @if shows content when a condition is true and shows nothing otherwise. Many screens need a second or third outcome instead of nothing: a login button for signed-out users, a spinner while data loads, or an error message when a request fails. You attach those outcomes to the same @if block with @else if and @else.
The basic shape
An @else block follows the closing brace of an @if block, on the same line or the next one. It renders when the @if condition is falsy.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-session',
template: `
@if (isLoggedIn()) {
<p>Welcome back!</p>
<button (click)="isLoggedIn.set(false)">Log out</button>
} @else {
<button (click)="isLoggedIn.set(true)">Log in</button>
}
`,
})
export class SessionComponent {
isLoggedIn = signal(false);
}This component needs no NgIf import and no <ng-template> reference. The blocks are part of the template syntax itself, so the component's imports array stays empty.
Chaining with @else if
When there are more than two outcomes, add one or more @else if blocks. Each has its own condition. Angular evaluates the conditions from top to bottom and renders the first block whose condition is truthy. It skips the rest without evaluating them. A final @else is optional and catches everything that no condition matched.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-stock-badge',
template: `
@if (stock() === 0) {
<span class="badge out">Out of stock</span>
} @else if (stock() < 5) {
<span class="badge low">Only {{ stock() }} left</span>
} @else {
<span class="badge ok">In stock</span>
}
`,
})
export class StockBadgeComponent {
stock = signal(3);
}With stock set to 3, the first condition is false and the second is true, so the "Only 3 left" badge renders. The order of the conditions matters. If you placed stock() < 5 first, a stock of 0 would match it and show "Only 0 left".
Only one branch renders
At any moment, at most one block in the chain exists in the DOM. When a signal changes and a different branch becomes the first true one, Angular removes the old branch's elements and creates the new branch's elements. State inside the removed branch, such as a child component's fields, is destroyed with it. Keep that in mind if a branch contains a form or a component that holds data.
The chain must stay together
@else if and @else only attach to the block directly before them. Putting other content between the blocks breaks the chain and produces a compile error.
@if (isAdmin()) {
<app-admin-panel />
}
<hr />
@else {
<app-user-panel />
}The template above fails to compile, because the <hr /> separates @else from its @if. Move the <hr /> inside a block or after the whole chain.
Two related rules are worth remembering:
- Each branch needs braces, even when it holds a single element.
@elsetakes no condition. If you write@else (something), the compiler reports an error. Use@else iffor that.
Choosing between @else if and @switch
A long @else if chain that compares one value against many constants is usually clearer as a @switch, which a later chapter covers. Keep @else if when the conditions differ in kind, for example stock() === 0, then stock() < 5, or when they use ranges and combined checks.
| Situation | Better fit |
|---|---|
| Two outcomes | `@if` with `@else` |
| Ranges or unrelated conditions | `@if` with `@else if` |
| One value compared with fixed options | `@switch` |
Common errors
- Placing content between
@ifand@else, which breaks the chain. - Ordering conditions from general to specific, so later branches never render.
- Expecting
@elseto take a condition. - Forgetting that a branch change destroys the old branch's state.
Exercise
A template has @if (score() >= 50) { <p>Pass</p> } @else if (score() >= 90) { <p>Distinction</p> } @else { <p>Fail</p> }. A score of 95 shows "Pass". Why, and how do you fix it?
Show answer
Angular renders the first block whose condition is true. A score of 95 satisfies score() >= 50, so the @else if for 90 is never evaluated. Reorder the chain so the most specific condition comes first: @if (score() >= 90) for Distinction, then @else if (score() >= 50) for Pass, then @else for Fail.
Exercise
Write a template fragment that shows "Loading..." when state() is 'loading', "Failed" when it is 'error', and the text "Done" otherwise, using only @if, @else if, and @else.
Show answer
@if (state() === 'loading') { <p>Loading...</p> } @else if (state() === 'error') { <p>Failed</p> } @else { <p>Done</p> }