AI Hints
Home›Angular Tutorial›@if, @else and @else if and @for
Angular · Lesson 38 of 120

@else and @else if

One of several.

⏱ 2 min read▶ Video at 46:19🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Often there are several cases. Sold out, only a few left, or plenty in stock. Exactly one message should show.

  • Several cases
  • One message
  • @else if, @else

Choosing one

At if checks its condition first. At else if adds another condition, checked only if the ones before it were false. At else catches everything else. So exactly one block is shown.

keyvalue
@ifchecked first
@else ifchecked next
@elseeverything else
Resultexactly one block

Stock messages

Stock starts at four. If it's zero, we show sold out. Else, if it's below three, we show how many are left. Otherwise, we show in stock. We sell two copies. Run it. Two copies are left, so the middle message shows.

app.tstypescript
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button id="sell" (click)="stock.update(s => s - 1)">Sell one</button>
    @if (stock() === 0) {
      <p class="error">Sold out</p>
    } @else if (stock() < 3) {
      <p>Only {{ stock() }} left</p>
    } @else {
      <p>In stock</p>
    }
  `,
})
export class App {
  stock = signal(4);
}
Also uses actions.json
[{"click": "#sell", "times": 2}]

Summary

At else if, and at else, chain conditions, so exactly one block shows. Next, lists, with at for.

Key takeaways
  • @if
  • @else if
  • @else
Next up: @for — repeat for every item