简体   繁体   中英

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

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 class="all-users" >
            <div class="nested-items"  *ngFor="let data of flattenedResponse[0]; let i=index;  " (click)="switchUsers(i)">
                <h4>{{i}}</h4>&nbsp;
                <img src="{{data.image}}" alt="profile">
            </div>
        </div>

Why not just do the following:

       <div class="all-users" >
        <div class="nested-items"  *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

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

The correct answer here is... you can't.

So there are some suggestions already, but personally I would avoid hacking your markup to get round the data structure the api returns. It's generally a bad idea to make your markup need to know too much about what your server does.

If the array your api returns is not in the best format for your markup - just create a new data array which is, and point your markup at that. It's best to do this in a service at the point you handle the api result, but if nothing else, do it in your.ts file.

have you try:

<div class="all-users">
  <div class="nested-items" *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 class="nested-items" *ngFor="let data of flattenedResponse[0] | slice:1; let i=index;  " (click)="switchUsers(i)"></div>

You can skip first index explicitly with *ngIf :

<div class="all-users" >
  <div class="nested-items"  *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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM