Angular 2. How to apply orderBy?

后端 未结 4 2009
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 04:13

I have a piece of code.



        
4条回答
  •  醉梦人生
    2020-12-03 04:32

    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, args: string): Array {
        array.sort((a: any, b: any) => {
          if (a < b) {
            return -1;
          } else if (a > b) {
            return 1;
          } else {
            return 0;
          }
        });
        return array;
      }
    }
    

    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: `
        
  • (...)
  • `, pipes: [ OrderByPipe ] }) (...)

提交回复
热议问题