How to show last item first in ngFor in Angular?

Viewed 1881

I have basic ngFor directive for display data from an Array, And i want to show the last item of array at the top and last item of array at bottom of result?

I saw few Questions in here tell not to use pipes on ngFor. So how can i achieve this behavior in TypeScript.

Thanks in advance.

2 Answers

You can also use something in html like if only take last one to first. Updated answer thanks to @Eliseo' s nice approach.

<p *ngIf="list.length>0">{{list[list.length-1]}}</p>
<ng-container *ngFor="let item of list; let last=last">
   <p *ngIf="!last"> {{item}}</p>
</ng-container>

You should use sort function to your array in code. Or create a dublicate for origin array and sort it instead.

Related