Rolando
Rolando

Reputation: 62624

How to get a reverse index in ngFor angular?

I am using the latest version of Angular and have an array "myarray" with 3 objects.

I want to make it so that I have divs looking like this:

<div id="num2">
<div id="num1">
<div id="num0">

Usually with *ngFor I do..

<div *ngFor="let something of myarray; let i = index" [attr.id]="'num'+i">

The problem is that creates an incrementally increasing so it is going from 0 to 2 instead of the reverse...

<div id="num0">
<div id="num1">
<div id="num2">

How can I make it such that it is decreasing?

Upvotes: 3

Views: 1719

Answers (3)

Minato
Minato

Reputation: 4533

@nicholas-k Answer is also right, but I think the best way to do it is by using count provided by ngFor directive.

<div *ngFor="let something of myarray; let cnt = count; let i = index;" [attr.id]="'num' + ( cnt - i - 1 )">

Upvotes: 5

Nicholas K
Nicholas K

Reputation: 15423

Use:

<div *ngFor="let something of myarray; let i = index;" 
     [attr.id]="'num' + (myarray.length - i - 1)">

Upvotes: 4

Hitech Hitesh
Hitech Hitesh

Reputation: 1635

You can set a length of the myarray into a variable and then subtract it with the index

Like this declare a variable

myarrayLength ;

In the function in which the value is set

this.myarrayLength =myarray.length;

Then you can subtract while in ng-for

<div *ngFor="let something of myarray; let i = index" [attr.id]="'num'+ (myarrayLength - i)">

Upvotes: 0

Related Questions