How to Display the Index in Reverse Order for *ngFor Angular

Let’s say that we have data in array e.g tasks = [‘task 5’, ‘task 4’, ‘task 3’, ‘task 2’, ‘task 1’]. Now when we will use ngFor then it will display the data like this:

*ngFor="let task of tasks; let i = index"
Task #{{i}}: {{task}}

Output:
Task 0: task 5
Task 1: task 4
Task 2: task 3
Task 3: task 2
Task 4: task 1

But we want to reverse the order of only the index. In order to do that in ts file of the angular components, define a veriable named as totalTasks: number. Now make it equal to the length of the array like this:

totalTasks: number;
totalTasks = tasks.length;

Now following modifications to the angular *ngFor will do the trick:

*ngFor="let task of tasks; let i = index"
Task #{{ totalTasks - i }}: {{task}}

and now the output will be:

Task 5: task 5
Task 4: task 4
Task 3: task 3
Task 2: task 2
Task 1: task 1

Leave a Reply

Your email address will not be published. Required fields are marked *