@if, @else if and @else
When Greenhouse opens, the plant list might still be loading, might have come back empty, or might be full. Each state needs its own message. Showing the wrong one, like "No plants yet" while data is still on its way, confuses people. The @if block handles this cleanly.
The rule
Top to bottom, first true branch wins, the rest are skipped.
@if (loading()) {
<p>Loading plants…</p>
} @else if (plants().length === 0) {
<p>No plants yet. Add your first one!</p>
} @else {
<app-plant-list [plants]="plants()" />
}- The condition goes in parentheses, the content in braces.
@else ifadds more conditions;@elsecatches everything left over. Both are optional.- Content in a false branch is not created at all. It is not hidden with CSS; it does not exist in the page.
- It is built into the template language, so there is nothing to import.
You can store the tested value under a short name with as, which saves repeating a long expression:
@if (selectedPlant(); as plant) {
<h2>{{ plant.name }}</h2>
<p>Water every {{ plant.everyDays }} days</p>
}Since selectedPlant() may be undefined, the block only renders once there is a plant, and inside it plant is known to be defined.
This replaces the older *ngIf="cond; else other" with its separate <ng-template #other>. The block form reads like ordinary code and keeps each branch next to its condition.
The shortcut
List the states from most specific to most general and write them in that order. Before writing, ask of each branch: "Could an earlier condition also be true here?" If so, the earlier one steals it.
Name the states
Loading, empty, has plants.
Drills
Answer fast — trust the rule.
What does Angular do with a branch whose condition is false?
Which syntax is correct?
With @if (count() > 0) {A} @else if (count() > 5) {B} @else {C}, what shows when count() is 8?
What does @if (selectedPlant(); as plant) do?
Remember
@if (cond) { }with optional@else ifand@else; no import needed.- First true branch wins, so order from most specific to most general.
- Trap: an earlier broad condition steals a later case;
asnames the tested value.
