Angular Control Flow

Angular Built-in Control Flow

For years, developers used structural directives like *ngIf and *ngFor to handle conditional rendering.

In Angular 17, the team introduced a brand new, incredibly fast Built-in Control Flow syntax.

This new syntax is built directly into the template engine, making it vastly superior in performance.


The @if Block

The new @if block completely replaces the traditional *ngIf directive.

It is much cleaner to read and does not require you to attach it to an HTML element.

It also provides highly intuitive @else if and @else blocks right out of the box!

@if Example:

@if (userStatus === 'admin') {
  <p>Welcome, Administrator!</p>
} @else if (userStatus === 'guest') {
  <p>Please log in.</p>
} @else {
  <p>Unknown user status.</p>
}

The @for Block

The @for block acts as the modern replacement for *ngFor.

It is heavily optimized and significantly reduces rendering times for large lists.

Unlike *ngFor, the new @for block strictly requires you to define a track property for performance tracking.

@for Example:

<ul>
  @for (item of shoppingList; track item.id) {
    <li>{{ item.name }}</li>
  }
</ul>

The @empty Block

One of the best features of the @for loop is the built-in @empty block.

If the array you are iterating over is completely empty, the @empty block automatically renders!

This eliminates the need to write an extra @if (array.length === 0) statement.

@empty Example:

@for (user of users; track user.id) {
  <div>{{ user.name }}</div>
} @empty {
  <p>No users found in the database!</p>
}

Exercise 1 of 2

?

What is a mandatory requirement when using the new @for block in Angular?

Exercise 2 of 2

?

Which block executes automatically if the array passed into an @for loop has zero items?