Angular 17 @for Loop with Index

Angular 17 @for Loop with Index Example

In this comprehensive tutorial, we will learn Angular 17 @for Loop with Index Example. If you have a question about angular 17 for loop index then I will give a simple example with a solution. This article goes in detailed on @for index angular 17 example. step by step explain angular 17 @for loop index example. Let’s see below example angular 17 @for index. You Can Learn Angular 17 Convert Date to mm/dd/yyyy Format Example

Angular 17 @for Loop with Index Example

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

Let’s see the Angular 17 @for Loop with Index 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: 'Dev Script School' },
    { id: 2, name: 'Msh Sayket' },
    { id: 3, name: 'Angular Tutorials' },
  ];
}

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. Dev Script School
1. Msh Sayket
2. Angular Tutorials

I hope it can help you…

Leave a Reply