Understanding the @for Loop

In Angular 17 to improve the developer experience @for is introduced. Before that, we were required to import the ngFor directive from @angular/common to iterate over arrays in Angular templates.

Syntax:

    @for (item of items; track item) {
// Html template to repeat
}
@empty {
// optional block to be displayed when collection is empty
}

@empty Block: You can optionally define an @empty block that will be rendered only if the collection is empty. This allows you to handle cases where there’s no data to display

Contextual variables

Contextual variables refers to the iteration variables. These variables are only accessible within the @for block and its nested child templates.

Following are the Contextual variables present in @for block:

Variable

Description

$count

Specifies number of items in a collection iterated over

$index

Specifies Index of the current row

$first

Specifies if the current row is the first row

$last

Specifies if the current row is the last row

$even

Specifies if the current row index is even

$odd

Specifies if the current row index is odd

@for Loop in Angular 17

In Angular, working with arrays, iterables, and object properties is a common task. The @for is a block that repeats a section of HTML for each item in a collection. It is commonly used to iterate over arrays or lists and generate dynamic content based on the data provided. In this article, we’ll explore how to use the @for loop in Angular 17 to create dynamic templates.

Similar Reads

Understanding the @for Loop

In Angular 17 to improve the developer experience @for is introduced. Before that, we were required to import the ngFor directive from @angular/common to iterate over arrays in Angular templates....

Steps to implement @for loop

Step 1: Create an angular project...