Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show last item first in ngFor in Angular?

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.

like image 778
pl-jay Avatar asked Jun 06 '20 15:06

pl-jay


People also ask

What is ngFor last?

last: boolean : True when the item is the last item in the iterable. even: boolean : True when the item has an even index in the iterable. odd: boolean : True when the item has an odd index in the iterable.

Why * is used in ngFor?

In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag.

What is * in ngFor angular?

*ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.

Which is the correct syntax of ngFor in angular?

The syntax is *ngFor="let <value> of <collection>" . <value> is a variable name of your choosing, <collection> is a property on your component which holds a collection, usually an array but anything that can be iterated over in a for-of loop.


1 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>
like image 146
mr. pc_coder Avatar answered Oct 20 '22 06:10

mr. pc_coder