本文介绍了角2排序依据管的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从angualr1翻译这个code到angular2,任何帮助?

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

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

这是我做了什么之后蒂埃里TEMPLIER的回答是:

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

HTML模板:

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

我敢肯定,误差在@Pipe,即时通讯试图理清托多斯阵列,通过todo.completed属性排序。首先todo.completed =假,比todo.complete = TRUE。

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.

一样,什么是ARGS:字符串参数? A和B,它们是什么?他们来自哪里?

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

推荐答案

您可以实现这个自定义的管道,它利用排序阵列的方法:

You could implement a custom pipe for this that leverages the sort method of arrays:

import { Pipe } from "angular2/core";

@Pipe({
  name: "sort"
})
export class ArraySortPipe {
  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;
  }
}

和使用再管,如下所述。不要忘了指定管道进入管道组件的属性:

And use then this pipe as described below. Don't forget to specify your pipe into the pipes attribute of the component:

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

这是与字符串值数组一个简单的示例,但你可以有一些先进的分拣处理(基于对象属性的对象数组,根据排序参数,......的情况下)。

It's a simple sample for arrays with string values but you can have some advanced sorting processing (based on object attributes in the case of object array, based on sorting parameters, ...).

下面是这个plunkr:。

Here is a plunkr for this: https://plnkr.co/edit/WbzqDDOqN1oAhvqMkQRQ?p=preview.

希望它可以帮助你,
蒂埃里

Hope it helps you,Thierry

这篇关于角2排序依据管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 10:55