Modern control flow in Angular (@if, @for, @switch)

Home » Tutorials » JavaScript » Modern control flow in Angular (@if, @for, @switch)
In this tutorial, we’ll talk about the modern control flow in Angular

In previous versions of Angular, template control flow was based on structural directives such as *ngIf, *ngFor, and *ngSwitch. I covered it in an earlier lesson.
The new control flow makes template code cleaner and more readable, while the core concept remains the same. However, there are several important details to note regarding the @for block (see the code example below):

  • the track keyword is now mandatory;
  • you can now use the @empty block.

The track keyword is required for collection rendering optimization. When working with collection items, track helps prevent unnecessary re-rendering when the collection changes, which improves performance.

The @empty block is a convenient addition to @for, allowing you to render a placeholder (text or component) when the collection is empty.

app.component

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  imports: [
  ],
  templateUrl: './app.html',
  styleUrl: './app.scss'
})
export class App {
  protected user =  {
    login: 'my login',
    roles: []
  };

  protected currentRole = 'manager2';
}

app.component.html

<!--@let myName = user$ | async;-->

@if (user?.login) {
  <p>{{user.login}}</p>

    @for (role of user.roles; track role) {
      <span>{{role}}</span><br>
    } @empty {
      <p>No roles for current user</p>
    }
} @else {
  <p>No login</p>
}


@switch (currentRole) {
  @case ('admin') {
    <p>Hello admin</p>
  }
  @case ('manager') {
    <p>Hello manager</p>
  }
  @default {
    <p>Unsupported role</p>
  }
}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This