Sub topic 3
Handling alternatives with @else if and @else
This chapter assumes you can write a standalone Angular component with an inline template, read signals with count(), and use basic @if blocks. It builds on the @if chapter. You will learn how to chain alternatives, how Angular chooses a branch, and which mistakes cause wrong output.
What an @if chain is
A single @if handles one yes-or-no decision. Real screens usually have more than two outcomes, such as "out of stock", "running low", and "available". You extend the block with @else if and @else. Together they form an @if chain.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-stock-badge',
template: `
@if (quantity() === 0) {
<span class="badge out">Out of stock</span>
} @else if (quantity() < 5) {
<span class="badge low">Only {{ quantity() }} left</span>
} @else {
<span class="badge ok">In stock</span>
}
<button (click)="quantity.set(quantity() - 1)" [disabled]="quantity() === 0">
Buy one
</button>
`,
})
export class StockBadgeComponent {
quantity = signal(6);
}Click "Buy one" repeatedly. The badge starts as "In stock", changes to "Only 4 left" when the quantity drops below 5, and ends as "Out of stock" at 0. The component imports nothing for the blocks. Control flow is part of the template syntax, so no module or directive import is needed.
How Angular picks a branch
Angular evaluates the chain from top to bottom and stops at the first condition that is truthy. It renders that block's content and ignores the rest of the chain. If no condition is truthy, it renders the @else block when one exists. If there is no @else, it renders nothing.
Three consequences follow from this model:
- Order matters. A broad condition placed early hides every branch below it.
- Conditions are not mutually exclusive. In the stock example,
quantity() < 5is also true when the quantity is 0. The branch for 0 works only because it comes first. You do not need to writequantity() > 0 && quantity() < 5. - Only one branch exists at a time. Angular does not render the other branches and hide them. Components, directives, and event listeners inside an inactive branch do not exist. When the chosen branch changes, Angular destroys the old branch's view and creates the new one.
Syntax rules
The rules are small, but breaking them produces compile errors:
@else iftakes a condition in parentheses, just like@if.@elsetakes no condition and no parentheses.@else ifand@elsemust follow the closing brace of the previous block of the same chain. Whitespace and newlines between}and@elseare allowed. Any other content between them ends the chain.- A chain can have any number of
@else ifblocks, but at most one@else, and it must come last. - You cannot write
@elseor@else ifon its own. It must belong to an@if.
import { Component } from '@angular/core';
@Component({
selector: 'app-broken-chain',
template: `
@if (ready) {
<p>Ready</p>
}
<hr />
@else {
<p>Not ready</p>
}
`,
})
export class BrokenChainComponent {
ready = false;
}This template fails to compile. The <hr /> ends the chain, so the @else has no @if to attach to. Move the <hr /> after the final closing brace.
Truthiness, not just booleans
Each condition is an ordinary template expression. Angular checks whether its value is truthy, using JavaScript rules. The values that behave unexpectedly are the ones to know:
| Value | Treated as |
|---|---|
| `true`, non-zero numbers, non-empty strings | truthy |
| `0`, `''`, `null`, `undefined`, `NaN`, `false` | falsy |
| `[]` (empty array) | truthy |
| `{}` (empty object) | truthy |
| a signal itself, such as `isReady` | truthy (it is a function) |
The last two rows cause the most bugs. @if (items) is true for an empty list, so it cannot detect "no items". Test the length explicitly: @if (items().length > 0). Likewise @if (isReady) is always true when isReady is a signal. Call it: @if (isReady()).
A realistic chain: loading, error, empty, data
Chains are most valuable when they express states that exclude each other in practice. A data panel usually has four: loading, failed, empty, and loaded. The order of the conditions encodes which state wins when several flags are set.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-results-panel',
template: `
@if (loading()) {
<p>Loading results...</p>
} @else if (error()) {
<p class="error">Failed: {{ error() }}</p>
<button (click)="retry()">Retry</button>
} @else if (results().length === 0) {
<p>No results found.</p>
} @else {
<p>{{ results().length }} results</p>
<p>First: {{ results()[0] }}</p>
}
`,
})
export class ResultsPanelComponent {
loading = signal(true);
error = signal<string | null>(null);
results = signal<string[]>([]);
retry() {
this.error.set(null);
this.loading.set(true);
setTimeout(() => {
this.results.set(['alpha', 'beta']);
this.loading.set(false);
}, 500);
}
}The chain is ordered on purpose:
loading()comes first, so a retry shows the spinner text even if an old error is still set.error()comes before the empty check. A failed request leavesresults()empty, and without this order the user would see "No results found" instead of the failure.- The empty check comes before the
@else, so the final block can assume at least one result exists.
If you swap the second and third branches, the error message never appears while the list is empty. Nothing warns you about it, because the template is valid either way.
Using @else if instead of nesting
You can often get the same result by nesting an @if inside an @else. The chain is shorter and avoids extra indentation.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-nested-vs-chain',
template: `
<!-- Nested: harder to read as it grows -->
@if (score() >= 90) {
<p>Grade A</p>
} @else {
@if (score() >= 80) {
<p>Grade B</p>
} @else {
<p>Grade C or lower</p>
}
}
<!-- Chained: same behavior -->
@if (score() >= 90) {
<p>Grade A</p>
} @else if (score() >= 80) {
<p>Grade B</p>
} @else {
<p>Grade C or lower</p>
}
`,
})
export class NestedVsChainComponent {
score = signal(85);
}Nest a block when the inner decision applies only inside one branch. Chain blocks when all the alternatives answer the same question.
When to prefer @switch
An @else if chain suits ranges, mixed conditions, and checks on different values. If every condition compares the same expression to a constant, such as status() === 'loading', status() === 'error', and so on, the intent is clearer in an @switch. A later chapter covers it. A good rule is that three or more equality checks on one value are a signal to switch.
Differences from *ngIf with else
Older templates used a template reference for the alternative:
<!-- Before -->
<p *ngIf="quantity > 0; else soldOut">In stock</p>
<ng-template #soldOut><p>Out of stock</p></ng-template>
<!-- After -->
@if (quantity > 0) {
<p>In stock</p>
} @else {
<p>Out of stock</p>
}The differences affect how you write and debug templates:
- Location. The
@elsecontent sits next to the condition. With*ngIf, theelsetarget could be defined anywhere in the template, so you had to search for it. - Chaining.
*ngIfhad noelse if. You nestedng-templatereferences or repeated conditions. The new syntax adds@else if. - Imports.
*ngIfrequired importingNgIf(orCommonModule) in each component. The@ifblock needs nothing. - Containers. Branches no longer need a wrapper element or
ng-container. A block can contain several sibling nodes directly.
Common errors with chains
- Missing parentheses on signals.
@else if (isAdmin)is always true whenisAdminis a signal. WriteisAdmin(). - Empty collections treated as false.
@if (list)passes for[]. Compare.length. - Broad conditions placed early.
@if (quantity() < 5)before@if (quantity() === 0)makes the "out of stock" branch unreachable. - Content between blocks. Any element or text between
}and@elseends the chain, as shown earlier. - Literal braces and at signs in text. The parser treats
@and}in template text as syntax. To print them, write the HTML entities@for@and}for}. - Condition with side effects. Conditions run on every change detection pass. Keep them to cheap reads, not method calls that compute or mutate state. Move expensive logic into a
computed()signal and read that.
Exercise
A component has items = signal<string[]>([]) and a template @if (items) { <p>{{ items().length }} items</p> } @else { <p>Nothing here</p> }. It always shows "0 items" and never "Nothing here". Name the two problems and write a corrected chain that shows "Nothing here" when the list is empty.
Show answer
First, items without parentheses is the signal function, which is always truthy, so the first branch always renders. Second, even with items(), an empty array is truthy, so the test must compare the length. Corrected: @if (items().length > 0) { <p>{{ items().length }} items</p> } @else { <p>Nothing here</p> }.
Exercise
Given the chain @if (n() < 10) { <p>small</p> } @else if (n() < 100) { <p>medium</p> } @else if (n() < 5) { <p>tiny</p> } @else { <p>large</p> }, what renders when n() is 3, and why is the tiny branch a mistake?
Show answer
It renders "small". Angular stops at the first truthy condition, and 3 < 10 is true. The tiny branch is unreachable: any value below 5 is also below 10, so the first condition catches it before the chain gets that far. To show "tiny", test n() < 5 first.