Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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

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.

Ordering the plant list statesStep 1 of 4
  1. Name the states

    Loading, empty, has plants.

Drills

Answer fast — trust the rule.

quick drill

What does Angular do with a branch whose condition is false?

quick drill

Which syntax is correct?

quick drill

With @if (count() > 0) {A} @else if (count() > 5) {B} @else {C}, what shows when count() is 8?

quick drill

What does @if (selectedPlant(); as plant) do?

Remember

  • @if (cond) { } with optional @else if and @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; as names the tested value.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainLoading, empty, or full

Greenhouse's plant list can be loading, loaded with no plants, or loaded with plants. Write the template with @if, @else if and @else, and explain why the order of the branches matters.