Angular 2.如何申请orderBy? [英] Angular 2. How to apply orderBy?

查看:104
本文介绍了Angular 2.如何申请orderBy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码。

<table class="table table-bordered table-condensed" cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Score</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="#participant of participants; #i = index">
            <td>{{i+1}}</td>
            <td>{{participant.username}}</td>
            <td>{{participant.score}}</td>
        </tr>
    </tbody>
</table>

在Angular 1中我有 orderBy 过滤器来按我的过滤器排序。但是我怎样才能以相同的方式在Angular 2中进行orderBy?谢谢。

In Angular 1 i have orderBy filter to order rows by my filter. But how can i do orderBy in Angular 2 the same way ? Thank you.

推荐答案

您需要为此实现自定义管道。这对应于创建一个由@Pipe修饰的类。这是一个例子。它的转换方法实际上将处理列表,您可以根据需要对其进行排序:

You need to implement a custom pipe for this. This corresponds to create a class decorated by @Pipe. Here is a sample. Its transform method will actually handle the list and you will be able to sort it as you want:

import { Pipe } from "angular2/core";

@Pipe({
  name: "orderby"
})
export class OrderByPipe {
  transform(array: Array<string>, args: string): Array<string> {
    array.sort((a: any, b: any) => {
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}

然后您可以在表达式中使用此管道,如下所述。例如在ngFor中。不要忘记将管道指定到您使用它的组件的管道属性中:

You can then use this pipe as described below in expressions. For example in an ngFor. Don't forget to specify your pipe into the pipes attribute of the component where you use it:

@Component({
  (...)
  template: `
    <li *ngFor="list | orderby"> (...) </li>
  `,
  pipes: [ OrderByPipe ]
})
(...)

这篇关于Angular 2.如何申请orderBy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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