@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.