OrderBy管道问题 [英] OrderBy pipe issue

查看:43
本文介绍了OrderBy管道问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将此代码从Angualr 1转换为Angular 2:

I'm not able to translate this code from Angualr 1 to Angular 2:

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

这是我在蒂埃里·坦佩利(Thierry Templier)的回答之后所做的事情:

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

组件模板:

*ngFor="#todo of todos | sort"

组件代码:

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

})

管道代码:

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

我正在尝试对Todo的数组进行排序,并按属性completed进行排序.首先是todo.completed = false,然后是todo.complete = true.

I'm trying to sort an array of Todos, ordered by the property completed. First todo.completed = false and then the todo.complete = true.

我不太了解transform方法以及如何在该方法和sort方法中传递参数.

I don't understand very well the transform method and how to pass the arguments in that method and in the sort method.

args: string参数是什么?什么是ab以及它们来自何处?

What is the args: string argument? What are a and b and where they come from?

推荐答案

我修改了@Thierry Templier的响应,因此管道可以按角度4对自定义对象进行排序:

I modified @Thierry Templier's response so the pipe can sort custom objects in angular 4:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "sort"
})
export class ArraySortPipe  implements PipeTransform {
  transform(array: any, field: string): any[] {
    if (!Array.isArray(array)) {
      return;
    }
    array.sort((a: any, b: any) => {
      if (a[field] < b[field]) {
        return -1;
      } else if (a[field] > b[field]) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}

并使用它:

*ngFor="let myObj of myArr | sort:'fieldName'"

希望这对某人有帮助.

这篇关于OrderBy管道问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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