Angular 2 OrderBy Pipe

2019-01-04 01:08发布

I'm not able to translate this code from angualr1 to angular2, any help?

ng-repeat="todo in todos | orderBy: 'completed'"

This is what i've done following the Thierry Templier's answer:

html template:

*ngFor="#todo of todos | sort"

component file:

@Component({
    selector: 'my-app',
    templateUrl: "./app/todo-list.component.html",
    providers: [TodoService],
    pipes: [ TodosSortPipe ]

})

pipe file:

import { Pipe } from "angular2/core";
import {Todo} from './todo';

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

I'm sure that the error is in the @Pipe, im trying to sort an array of Todos, ordered by the property todo.completed. First todo.completed = false and than the todo.complete = true.

I'm honest, I didn't understand very well the transform method and how to pass the arguments in that method and in the sort method.

Like, what is the args: string argument? a and b, what are they? where they come from?

14条回答
可以哭但决不认输i
2楼-- · 2019-01-04 01:57

Recommend u use lodash with angular, then your pipe will be next:

import {Pipe, PipeTransform} from '@angular/core';
import * as _ from 'lodash'
@Pipe({
    name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {

    transform(array: Array<any>, args?: any): any {
        return _.sortBy(array, [args]);
    }

}

and use it in html like

*ngFor = "#todo of todos | orderBy:'completed'"

and don't forget add Pipe to your module

@NgModule({
    ...,
    declarations: [OrderByPipe, ...],
    ...
})
查看更多
【Aperson】
3楼-- · 2019-01-04 01:58

You can use this for objects:

@Pipe({
  name: 'sort',
})
export class SortPipe implements PipeTransform {

  transform(array: any[], field: string): any[] {
    return array.sort((a, b) => a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0);
  }

}
查看更多
登录 后发表回答