Loop Iteration Indexes in Angular
When looping through *ngFor
and @for
, you can get not only the array elements, but also their numbers. Let's see how this is done. Let's say we have an array in the main component:
export class AppComponent {
public arr: string[] = ['a', 'b', 'c', 'd'];
}
Let's print both its elements and numbers.
For the *ngFor
directive, a special trick is used for this:
<ul>
<li *ngFor="let el of arr; let i = index">
{{ i }}
{{ el }}
</li>
</ul>
And for the @for
construction, you can simply take and use this variable inside the loop:
<ul>
@for (el of arr; track $index) {
<li>
{{ $index }}
{{ el }}
</li>
}
</ul>
Given an array:
export class AppComponent {
public arr: string[] = ['a', 'b', 'c', 'd'];
}
Print its numbers, but so that they start with one, not zero.