In this article we'll see how to use @for block in Angular with examples.
@for in Angular
The @for block in Angular is a built-in control flow syntax used to repeatedly loop and render content in a template for each
item in an iterable.
@for control flow statement is added in Angular 17 and provides a cleaner syntax than using the
ngFor directive in Angular.
Syntax of @for block
@for (item of items; track item.id) {
<!-- Content to repeat for each item -->
} @empty {
<!-- Optional content to display if the collection is empty -->
}
Here item variable is assigned the value of each item in the collection.
The 'items' represents the collection to be iterated over. This collection can be an array, a string, or anything that is
iterable.
The value of the track expression should be a unique identifier for each item in the collection for example id property, or a
value that uniquely identifies each item. Note that the track expression is required.
@empty: This is an optional block that renders its content only if the items collection is empty.
@for example in Angular
1. Looping a simple array of strings
fordemo.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-fordemo',
standalone: true,
imports: [],
templateUrl: './fordemo.component.html',
styleUrl: './fordemo.component.css'
})
export class FordemoComponent {
items = ['Ram', 'CPU', 'Mouse', 'Keyboard'];
}
fordemo.component.html
<ul>
@for(item of items; track item){
<li>{{item}}</li>
}
</ul>
Then import the component in the AppComponent
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { FordemoComponent } from "./ControlFlow/fordemo/fordemo.component";
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, FordemoComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'myApp';
}
And you are ready to use it in app.component.html
<app-fordemo />
That should give you the output as a list of items
• Ram
• CPU
• Mouse
• Keyboard
2. Looping an array of objects
fordemo.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-fordemo',
standalone: true,
imports: [],
templateUrl: './fordemo.component.html',
styleUrl: './fordemo.component.css'
})
export class FordemoComponent {
products = [
{id:1, name:'Ram', price:45.67},
{id:2, name:'CPU', price:175.67},
{id:3, name:'Mouse', price:23},
{id:3, name:'Keyboard', price:50}
];
}
fordemo.component.html
<ul>
@for(product of products; track product.id){
<li>{{product.name}} {{product.price}}</li>
}
</ul>
As you can see now item.id is used as track expression, which should be unique for each item.
3. @for with $empty
<ul>
@for(item of items; track $index){
<li>{{item}}</li>
}@empty {
<li>There are no items.</li>
}
</ul>
In the ts file, if items array is empty
items = [];
then $empty block is rendered.
Why is track expression required
As already mentioned, the track expression is required, omitting it results in "@for loop must have a "track" expression" error.
Providing track expression is crucial for performance optimization. It helps Angular efficiently identify and update DOM elements
when the underlying data changes, preventing unnecessary re-rendering of the entire list.
Track expression determines a key used to associate array items with the views in the DOM. Having that clear item identity
allows Angular to execute a minimal set of DOM operations as items are added, removed or moved in a collection.
For example, if you are adding a new element to an array of length 100, Angular should be able to identify its id as a new id
and just append that new element to the DOM, without having to re-render all the other elements.
Using $index as tracking mechanism
$index is one of the implicit variable available with @for, which provides the index of the current row. This $index can also
be used as track expression.
<ul>
@for(item of items; track $index){
<li>{{item}}</li>
}
</ul>
track $index should only be preferred as tracking mechanism if collection which is iterated is static. For dynamic collections
with frequent additions, deletions, or reordering, opt for a unique property of each item as the tracking key.
Contextual variables available with @for
Within the @for block, you can access several built-in contextual variables using a let expression, such as:
- $count- Number of items in a collection iterated over
- $index- Index of the current row
- $first- Whether the current row is the first row
- $last- Whether the current row is the last row
- $even- Whether the current row index is even
- $odd- Whether the current row index is odd
@for with $index example
Template code
@for(product of products; track product.id; let idx = $index){
<p>Product #{{ idx+1 }}: {{product.name}} {{product.price}}</p>
}
If you call it with the following array in .ts file
products = [
{id:1, name:'Ram', price:45.67},
{id:2, name:'CPU', price:175.67},
{id:3, name:'Mouse', price:23},
{id:3, name:'Keyboard', price:50}
];
Then the output is
Product #1: Ram 45.67
Product #2: CPU 175.67
Product #3: Mouse 23
Product #4: Keyboard 50
Note that index is zero based.
@for with $odd and $even example
If you want to render a table with odd and even rows in different colours then that can be done using the $odd or $even
implicit variable.
fordemo.component.html
<h2>Product Details</h2>
<table border="1">
<tr>
<th>S. No</th>
<th>Id</th>
<th>Name</th>
<th>Price</th>
</tr>
@for(product of products; track product.id; let idx = $index; let odd = $odd){
<tr [class.bg]="!odd">
<td>{{idx+1}}</td>
<td>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
</tr>
}
</table>
Note that,
class binding in Angular is used here to bind CSS class. The variable odd returns true or false based on whether the row
position is even or odd.
fordemo.component.css
.bg{
background-color: yellow;
}
fordemo.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-fordemo',
standalone: true,
imports: [],
templateUrl: './fordemo.component.html',
styleUrl: './fordemo.component.css'
})
export class FordemoComponent {
products = [
{id:1, name:'Ram', price:45.67},
{id:2, name:'CPU', price:175.67},
{id:3, name:'Mouse', price:23},
{id:3, name:'Keyboard', price:50}
];
}
That's all for this topic @for in Angular With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
-
@if in Angular With Examples
-
Angular ngSwitch Directive With Examples
-
Angular ngIf Directive With Examples
-
Angular ngStyle Directive With Examples
-
Directives in Angular
You may also like-
-
Angular First App - Hello world Example
-
Angular Class Binding With Examples
-
Angular Two-Way Data Binding With Examples
-
CanDeactivate Guard in Angular With Example
-
Unmodifiable or Immutable List in Java
-
Initializer Block in Java
-
java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
-
Python Program to Display Armstrong Numbers