0
0
AngularConceptBeginner · 4 min read

@if in Angular: What It Is and How to Use It

@if in Angular is a new directive used for conditional rendering of templates based on a condition. It allows you to show or hide parts of the UI easily by checking if a condition is true or false.
⚙️

How It Works

The @if directive in Angular works like a gatekeeper that decides whether a piece of the user interface should be visible or not. Think of it like a light switch: if the condition is true, the light (UI element) turns on; if false, it stays off.

Under the hood, Angular evaluates the condition you provide to @if. If the condition is true, Angular inserts the template content into the DOM. If false, it removes that content, keeping the page clean and efficient.

This directive is part of Angular's new control flow syntax introduced in Angular 16, making templates easier to read and write compared to the older *ngIf syntax.

💻

Example

This example shows how to use @if to display a message only when a user is logged in.

angular
<ng-template #loggedInMessage>
  <p>Welcome back, user!</p>
</ng-template>

<div @if="isLoggedIn; then loggedInMessage">
</div>

<script>
  import { Component, signal } from '@angular/core';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
  })
  export class AppComponent {
    isLoggedIn = signal(true); // Change to false to hide message
  }
</script>
Output
Welcome back, user!
🎯

When to Use

Use @if when you want to show or hide parts of your Angular app based on conditions like user login status, feature flags, or data availability. It helps keep your UI clean by only rendering what is needed.

For example, you might use @if to show a loading spinner while data is loading, or to display different content for logged-in versus guest users.

Key Points

  • @if is Angular's new way to conditionally render templates.
  • It replaces the older *ngIf directive with cleaner syntax.
  • Only renders content when the condition is true, improving performance.
  • Works well with Angular's reactive signals for dynamic UI updates.

Key Takeaways

@if controls whether UI parts appear based on a condition.
It is simpler and cleaner than the older *ngIf syntax.
Use it to improve UI clarity and app performance by rendering only needed content.
Works seamlessly with Angular's reactive signals for dynamic updates.