Angular 18 @for Loop with Index Example

By Hardik Savani August 27, 2024 Category : Angular

Today, I will let you know example of angular 18 @for index. Here you will learn angular 18 for loop index. This post will give you a simple example of @for index angular 18 example. you'll learn angular 18 @for loop index example. follow the below step for angular 18 @for index.

Angular provides for loop using ngFor but, Angular 18 changed the for loop flow flow with new syntax with index. You can use @for with index in angular 18. You can see one be one example with output and a new for loop with index and track.

Let's see the simple example code:

Example:

You can update the following code with the app.component.ts file:

src/app/app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
  
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  users = [
    { id: 1, name: 'Hardik Savani' },
    { id: 2, name: 'Vimal Kashiyani' },
    { id: 3, name: 'Harshad Pathak' },
  ];
    
}

Here, update the app.component.html file:

src/app/app.component.html

<div class="container">
  
    <!-- New @for loop -->
    <ul>
      @for (user of users; track user.id; let index = $index) {
        <li>{{ index }}. {{ user.name }}</li>
      } @empty {
        <span>Empty list of users</span>
      }
    </ul>
   
    <!-- Old ngFor loop -->
    <li *ngFor="let user of users; let i = index;">
      {{ i }}. {{user.name}}
    </li>
  
</div>

Output:

You will see the following output:

0. Hardik Savani
1. Vimal Kashiyani
2. Harshad Pathak

I hope it can help you...

Shares