0
votes

I am new to Angular and just wanted to understand if I can use the ngFor directive without the let item of items; let i = index syntax

Is there any other way of getting hold of the index while iterating an array when using ngFor

My Sample App

<div *ngFor="let oddNumber of oddNumbers; let i = index">
   <app-odd *ngIf="oddNumbers[i]" [number]="oddNumbers[i]"></app-odd>
   <app-even *ngIf="evenNumbers[i]" [number]="evenNumbers[i]"></app-even>
</div>
2

2 Answers

1
votes

Internally the micro-syntax *ngFor is expanded to the usual binding syntax [ngForOf].

Eg.

<div *ngFor="let oddNumber of oddNumbers; let i = index">
  ...
</div>

is expanded to

<ng-template ngFor let-oddNumber [ngForOf]="oddNumbers" let-i="index">
  <div>...</div>
</ng-template>

Without the let oddNumber of oddNumbers, the let-i="index" doesn't have any context. So it isn't possible to use the *ngFor directive without the let oddNumber of oddNumbers input.

However if you wish to access only the odd or even items in the loop, *ngFor has boolean local variables like odd and even similar to index.

<div *ngFor="let item of items; let i=index; let even=even; let odd=odd">
  <ng-container *ngIf="even">
    <!-- item in even position -->
    ...
  </ng-container>
  <ng-container *ngIf="odd">
    <!-- item in odd position -->
    ...
  </ng-container>
</div>
0
votes

Seems like this is the right way to save the index of each array item in the HTML file: ngFor with index as value in attribute

But if you are looking for other ways to save the index, you can try to iterate through the array in the Ts file and then do the desired action based on the index number.