Angular Start NgFor Index From 1
Answer :
*ngFor="let item of items | slice:1; let i = index;
SlicePipe
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:
Sample Book Title
Another book title
...
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()
andString.prototype.slice()
.When operating on an
Array
, the returnedArray
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.
Comments
Post a Comment