Angular start ngFor index from 1

Is it possible to start ngFor index from 1 instead of 0?

let data of datas;let i=index+1

didn't work.


Solution 1:

 *ngFor="let item of items | slice:1; let i = index;

SlicePipe

Solution 2:

There are 2 possible answers to the question, depending on what was actually being asked.

If the intent is to skip the first element of the array, then the answers involving slice are in the right direction.

However, if the intent is to simply shift the index while still iterating over all of the array, then slice is NOT the correct approach, as it will skip the 0th element in the array, thereby outputting only n-1 items from an array of length n.

@Taylor gave a real-world example of when the index might need to be shifted for display purposes, such as when outputting a list where the first entry should read 1, not 0.

Here's another similar example:

<li *ngFor="let book of books; let i = index">
    {{ i + 1 }}.  {{ book.title }}
</li>

which would produce output like:

  1. Sample Book Title

  2. Another book title

...

Solution 3:

That's not possible, but you could use Array.prototype.slice() to skip the first element:

<li *ngFor="let item of list.slice(1)">{{ item }}</li>

The SlicePipe is also an option if you prefer that syntax:

<li *ngFor="let item of items | slice:1">{{ item }}</li>

Description

All behavior is based on the expected behavior of the JavaScript API Array.prototype.slice() and String.prototype.slice().

When operating on an Array, the returned Array is always a copy even when all the elements are being returned.

If you also need the index to match, just add the number of elements you skipped to it:

<li *ngFor="let item of list.slice(1); let i = index">{{ i + 1 }} {{ item }}</li>

Or:

<li *ngFor="let item of items | slice:1; let i = index">{{ i + 1 }} {{ item }}</li>

Anyway, if you need to put too much logic in the template to make this work for your use case, then you should probably move that logic to the controller and just build another array with the exact elements and data that you need or cache the sliced array to avoid creating a new one if the data hasn't changed.

Solution 4:

  <li *ngFor="let info of data; let i = index">
    {{i + 1}} {{info.title}}
  </li>

Solution 5:

You can't at least for now, it seems the team behind angular 2 is trying to keep ngFor really simple, there's a similar issue opened on Angular 2 repo about doing multiple assigning of the index and the answer was:

syntax has to be simple for tools to support it.