Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert Angular 2 *ngFor

Tags:

angular

<li *ngFor="#user of users ">     {{ user.name }} is {{ user.age }} years old. </li> 

Is it possible to invert the ngFor that the items are added bottom up?

like image 654
daniel Avatar asked Feb 29 '16 15:02

daniel


People also ask

How do you reverse the order of NgFor?

You can simply use JavaScript's . reverse() on the array. Don't need an angular specific solution.

What is * in NgFor angular?

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.

How do you reverse a list in JavaScript?

JavaScript Array reverse()The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.


2 Answers

You can simply use JavaScript's .reverse() on the array. Don't need an angular specific solution.

<li *ngFor="#user of users.slice().reverse() ">    {{ user.name }} is {{ user.age }} years old. </li> 

See more here: https://www.w3schools.com/jsref/jsref_reverse.asp

like image 107
André Góis Avatar answered Sep 22 '22 16:09

André Góis


You need to implement a custom pipe that leverage the reverse method of JavaScript array:

import { Pipe, PipeTransform } from '@angular/core';  @Pipe({ name: 'reverse' })  export class ReversePipe implements PipeTransform {   transform(value) {     return value.slice().reverse();   } } 

You can use it like that:

<li *ngFor="let user of users | reverse">     {{ user.name }} is {{ user.age }} years old. </li> 

Don't forget to add the pipe in the pipes attribute of your component.

like image 38
Thierry Templier Avatar answered Sep 21 '22 16:09

Thierry Templier