Skip to the workspace
Pebellslearn by building
Template Syntax and Lifecycle  ›  Lesson

@if, @else if and @else

@if 12 minThe built-in @if block renders its content only when a condition is true, with optional @else if and @else branches, and can store the tested value under a name with as.

angular / @if, @else if and @else

Explore each scene at your own pace.

01 · The rule

The rule

@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 if adds more conditions; @else catches 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.