Angular 2 ngFor - 使用索引的反向输出顺序 [英] Angular 2 ngFor - reverse order of output using the index

查看:769
本文介绍了Angular 2 ngFor - 使用索引的反向输出顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Angular 2中学习有关过滤和排序的内容。我似乎无法找到任何合适的资源,而且我仍然坚持如何使用索引以相反的顺序对ngFor输出进行排序。我写了以下管道,它一直给我错误,数组切片不是函数。

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();
    }
}

和我的ngfor看起来像这样。

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>


推荐答案

对于这类常见用例,我建议你使用ng-pipes模块的反向管道:
https://github.com/ danrevah / ng-pipes#reverse-1

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

来自DOCS:

在控制器中:

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

视图中的

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

这篇关于Angular 2 ngFor - 使用索引的反向输出顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆