How to use the new Angular control-flow syntax


Angular recently turned 13 years old.

Happy birthday Angular!

casual-life-3d-birthday-cake

And with that came the release of Angular 17!

This latest release sets a new standard for what the Angular framework can do.

In this article I want to explain the coolest feature about the Angular 17 release.

THE NEW CONTROL FLOW SYNTAX.

🥳 🥳 🥳

Why the new control flow syntax in Angular 17?

An Angular survey found that developers often checked documentation to remember the syntax of ngFor, ngIf, etc...

Even Minko who's a popular dev on the Angular team admitted he often had to refer to the docs to remember Angular control flow syntax.

So they decided to take a shot at making it simpler.

My first and favorite feature is the @for loop.

@for loops (with up to 90% faster runtime performance)

In the older versions of Angular we used the *ngFor to loop through an array of items.

Like this.

<table>
    <tr *ngFor="let person of people">
      <td>{{ person.firstName }}</td>
    </tr>
</table>

In Angular 17 we can replace the old *ngFor with the new @for block.

<table>
  @for (person of people; track person.firstName) {
    <tr>
      <td>{{ person.firstName }}</td>
    </tr>
  }
</table>

And we can even add a condition if our list is empty.

<table>
  @for (person of people; track person.firstName) {
    <tr>
      <td>{{ person.firstName }}</td>
    </tr>
  }@empty {
    <tr>No data</tr>
  }
</table>

According to the Angular 17 release announcement the @for loop has up to a 90% faster runtime performance improvement.

@if-else

In the older versions of Angular we used *ngIf and also the *ngIf="condition; else elseBlock".

That all gets better in Angular 17.

We can now do this basic @if syntax.

@if (authenticated) {
  <button>Logout</button>
}

And we can also use an if-else syntax like this.

@if (authenticated) {
  <button>Logout</button>
} @else {
  <button>Sign up</button>
}

@switch statements

And then there are the new switch statements.

These give us a concise way to handle multiple cases within our Angular code.

When there are multiple conditions to be checked in an if-else block, switch statements are probably a better option.

@switch (userType) {
  @case ('ADMIN') {
    <p>Administrator</p>
  }
  @case ('CLIENT') {
    <p>Client</p>
  }
  @default {
    <p>Anonymous</p>
  }
}

The helpful Angular team created a schematic to help you upgrade older projects to the new syntax.

First you'll have to upgrade your project to Angular version 17. Then run the following command, follow the prompts, and let it automatically migrate your project.

ng generate @angular/core:control-flow

In summary, the new control flow syntax in Angular 17 provide developers with a more memorable way to control the rendering flow of their Angular app.

What cool things will come in Angular 18?

signature

Daniel Kreider

Credits