Home > database >  How to start loop from index 1 instead of index 0 in *ngFor loop in angular?
How to start loop from index 1 instead of index 0 in *ngFor loop in angular?

Time:01-09

I am currently getting some data from a dummy api, data from response starts from 1 and the index is currently starting from 0.

How I can start the index loop from 1 instead of 0?

Following the html for *ngFor below:

component.html

       <div  >
            <div   *ngFor="let data of flattenedResponse[0]; let i=index;  " (click)="switchUsers(i)">
                <h4>{{i}}</h4>&nbsp;
                <img src="{{data.image}}" alt="profile">
            </div>
        </div>

CodePudding user response:

Why not just do the following:

       <div  >
        <div   *ngFor="let data of flattenedResponse[0]; let i=index;  " (click)="switchUsers(i)">
            <h4>{{i   1}}</h4>&nbsp;
            <img src="{{data.image}}" alt="profile">
        </div>
    </div>

I don't know of a way to change where the index starts, but this way works fine for most cases

CodePudding user response:

have you try :

<div >
  <div  *ngFor="let data of flattenedResponse[0]; let i=index;  " (click)="switchUsers(i 1)">
    <h4>{{i 1}}</h4>&nbsp; <img src="{{data.image}}" alt="profile">
  </div>
</div>

or you can just skip first element like this :

<div  *ngFor="let data of flattenedResponse[0] | slice:1; let i=index;  " (click)="switchUsers(i)"></div>

CodePudding user response:

You can skip first index explicitly with *ngIf:

<div  >
  <div   *ngFor="let data of flattenedResponse[0]; let i=index;" (click)="switchUsers(i)">
    <ng-container *ngIf="index !== 0">
      <h4>{{i}}</h4>&nbsp;
        <img src="{{data.image}}" alt="profile">
      </div>
    </ng-container>
  </div>
</div>
  • Related