Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 ngFor - reverse order of output using the index

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>
like image 378
Hamburgersn Heroin Avatar asked Nov 15 '16 19:11

Hamburgersn Heroin


4 Answers

I would add .slice() as well

*ngFor="let advert of activeAdverts.slice().reverse() let i = index;"
like image 166
Chris Skura Avatar answered Oct 25 '22 02:10

Chris Skura


Use this

*ngFor="let item of items.slice().reverse()"
like image 23
Trilok Singh Avatar answered Oct 25 '22 01:10

Trilok Singh


I think @BhaskerYadav gave the best answer. Changing the original array is a bad idea and his/her idea has no side-effects, performance or otherwise. IMHO it just needs a slight improvement as all that index dereferencing is unreadable at scale.

<tr *ngFor="let _ of activeAdverts; let i = index">
  <ng-container *ngIf="activeAdverts[activeAdverts.length-i-1] as advert">
    <td>{{advert.p}}</td>
    <td>{{advert.q}}</td>
    ...
  </ng-container>
</tr>
like image 20
Mark Florence Avatar answered Oct 25 '22 01:10

Mark Florence


Using the following method u can reverse the output, but orignal array won't be modified,

 <tr *ngFor="let advert of activeAdverts; let i = index" >
           <td>{{activeAdverts[activeAdverts.length-i-1]}}</td>
  </tr>
like image 21
BhaskerYadav Avatar answered Oct 25 '22 01:10

BhaskerYadav