Angular start ng for index from 1

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

let data of datas;let i=index+1 

does not work.

+20
source share
6 answers
  *ngFor="let item of items | slice:1; let i = index; 

Slicepipe

+23
source

This is not possible, but you can use Array.prototype.slice() to skip the first element:

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

SlicePipe is also an option if you prefer this 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 working with Array returned Array always a copy, even when all elements are returned.

If you also need an index to match, just add the number of elements 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> 

In any case, if you need to put too much logic in the template for this to work for your use case, you should probably move that logic to the controller and just create another array with the exact elements and data you need, or cache the sliced fragment. an array to avoid creating a new one if the data has not changed.

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

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

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

However, if the goal is to simply shift the index while continuing to iterate over the entire array, then slicing is NOT the right approach, since it will skip the 0th element in the array, thereby only removing n-1 elements from the array of length n .

@Taylor gave a real example of when an index may need an offset for display purposes, for example, when listing, where the first record should read 1, not 0.

Here is another similar example:

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

which will produce a conclusion like:

  1. Sample book title

  2. Another title of the book

...

+8
source

You cannot at least at the moment, it seems that the team behind angular 2 is trying to save ngFor very simply, there is a similar problem open on angular 2 repo about performing multiple index assignment and the answer was:

Syntax

should be simple for tools to support it.

+4
source

We can approach it as shown below for custom tags / tags by default:

  <custom-tag *ngFor="let item of items; let i = index" [text]="Item + getIndex(i)"></custom-tag> 

In Javascript:

 function getIndex(i) {return Number(i + 1).toString();} 
0
source

All Articles