Steps to implement @for loop

Step 1: Create an angular project

You can use the following command to create a new angular project.

ng new my-angular-app

Folder Structure

@for Loop in Angular 17

Dependencies

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Example 1: Simple for loop

HTML
<!-- app.component.html -->

<ul>
    @for (fruit of fruits; track fruit) {
    <li>{{ fruit }}</li>
    }
</ul>
JavaScript
// app.component.ts

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    standalone: true,
    templateUrl: './app.component.html',
    styleUrl: './app.component.css',
})
export class AppComponent {
    title = 'Angular Material 17 File Upload';

    fruits = ['Apple', 'Bannana', 'Guava', 'Pineapple'];
}

Output

In this example, fruits is an array containing names of fruits, each <li> element will be generated dynamically for each fruit in the array.

Example 2: @for loop with track as index

HTML
<!-- app.component.html -->

<ul>
    @for (fruit of fruits; track $index) {
    <li>{{ $index }}. {{ fruit }}</li>
    }
  </ul>
  
JavaScript
// app.component.ts

// app.component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    standalone: true,
    templateUrl: './app.component.html',
    styleUrl: './app.component.css',
})
export class AppComponent {

    fruits = ['Apple', 'Bannana', 'Guava', 'Pineapple'];
}

Output:

In this example we are iterating over an array of fruit names and rendering them with the help of @for block. We are also displaying the index of each fruit using the $index variable.



@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...