Skip to content

@for(...)

Published on January 1, 2024

The new @for which we can use to replace *ngFor is available from Angular 17. The new syntax is much cleaner and easier to read and write, and more powerful.
Let’s look at the following example and disect the main features and benefits of the new syntax.

import { Component, ChangeDetectionStrategy } from '@angular/core';
import {OldNgForComponent} from './old-ngfor.component';
import {NewForComponent} from './new-for.component';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-root',
standalone: true,
imports: [OldNgForComponent, NewForComponent],
template: `
  <h1>*ngFor -> &#64;for</h1>
	<old-ngfor></old-ngfor>
	<new-for></new-for>
`,
})
export class AppComponent {	
}
Read-only

track

in the new @for control flow syntax, supplying track is mandatory. According to angular docs, a lot of angular apps performance issues were caused by *ngFor loops without trackBy, now the track is mandatory with a much simpler syntax.
You can now choose a propery from the iterated object to track by, and angular will use it to track changes in the array.
You can also use the $index context variable to track by index, but it’s better if you have a primary key on the object to use that as the track property.

empty block

After the @for block you can add an @empty block, which will be rendered if the array is empty.
Before the new control flow syntax we had to use *ngIf to check if the array is empty, and then render the empty block.

context variables

The same context variables that were available in *ngFor are available in @for as well:

  • $index - the index of the current item in the array
  • $first - true if the current item is the first item in the array
  • $last - true if the current item is the last item in the array
  • $even - true if the current item index is even
  • $odd - true if the current item index is odd

Summary

It’s recommended to stop using *ngFor and use the new @for control flow syntax instead. There are few advantages for using the new @for syntax:

  • easier to understand the @for block
  • easier to supply track
  • mandatory track will prevent performance issues
  • easier to render an empty block