Return to site

Angular 17: New control flow syntax

· angular

New “for” loop syntaxNew “If — then — else” syntax

@if (a > b) {
  {{a}} is greater than {{b}}
} @else if (b > a) {
  {{a}} is less than {{b}}
} @else {
  {{a}} is equal to {{b}}
}

New “for” loop syntax

@for (item of items; track item.name) {
  <li> {{ item.name }} </li>
} @empty {
  <li> There are no items. </li>
}

New “switch — case” syntax

@switch (page) {
  @case (1) {
    <p>Viewing content of first page</p>
  }
  @case (2) {
    <p>Viewing content of second page</p>
  }
  @default {
     <p>No page selected</p>
  }
}

Important notes

While those new syntaxes are available with Angular 17, it is essential to mention that:

  • Legacy Angular directives such as ngIf, ngFor, and ngSwitch are not deprecated and are not going away any time soon.
  • You can use both syntaxes in your Angular 17+ app if you want
  • There is an automated Angular CLI migration command available if you want to replace the legacy syntax automatically: ng g @angular/core:control-flow
  • It’s not just about syntax: The Angular team measured up to 90% speed performance improvements when using the new syntax and an average of 30% speed improvement on the Angular Material repo.