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

@if

Show or hide.

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

Pages often show something only sometimes. Details when you ask for them, or a warning when stock is low. Angular's at if block does this.

  • Show something sometimes
  • Details, warnings
  • @if

The @if block

At if takes a condition, in round brackets. If the condition is true, the content inside the curly braces is shown. If it's false, the content is removed from the page completely. When signals in the condition change, Angular checks again.

keyvalue
@if (condition) { ... }show when true
Falseremoved from the page
Conditionany TypeScript expression
Signalschecked again on change

Show details

The details button flips the show details signal, between true and false. The first at if shows the description, only when show details is true. The second shows a warning, when stock is below three. We click details. Run it. The description appeared. And the stock warning shows too, because the stock is two.

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

@Component({
  selector: 'app-root',
  template: `
    <h2>Dune</h2>
    <button (click)="showDetails.set(!showDetails())">Details</button>
    @if (showDetails()) {
      <p>A science fiction classic, set on the desert planet Arrakis.</p>
    }
    @if (stock() < 3) {
      <p class="error">Hurry, only {{ stock() }} left!</p>
    }
  `,
})
export class App {
  showDetails = signal(false);
  stock = signal(2);
}
Also uses actions.json
[{"click": "button"}]

Summary

At if shows its content only when the condition is true, and removes it when false. Next, at else, and at else if.

Key takeaways
  • @if (cond) { }
  • Removed when false
  • Signals re-checked
Next up: @else and @else if — one of several