Angular 2 ngFor - reverse order of output using the index

Hamburgersn Heroin picture Hamburgersn Heroin · Nov 15, 2016 · Viewed 25.7k times · Source

Trying to learn something about filtering and ordering in Angular 2. I can't seem to find any decent resources and I'm stuck at how to order an ngFor output in reverse order using the index. I have written the the following pipe put it keeps giving me errors that array slice in not a function.

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(arr) {
        var copy = arr.slice();
        return copy.reverse();
    }
}

and my ngfor looks like this.

<div class="table-row generic" *ngFor="let advert of activeAdverts | reverse let i = index;" [attr.data-index]="i" (click)="viewAd(advert.title)">      
    <div class="table-cell white-text">{{ i+1 }}</div>                    
    <div class="table-cell white-text">{{advert.title}}</div>
    <div class="table-cell green-text">{{advert.advert}}</div>
</div>

Answer

D_R picture D_R · Dec 24, 2016

For such common use cases, I would suggest you to use reverse pipe from ng-pipes module: https://github.com/danrevah/ng-pipes#reverse-1

From the DOCS:

in the controller:

this.items = [1, 2, 3];

in the view:

<li *ngFor="let item of items | reverse"> <!-- Array: [3, 2, 1] -->