OrderBy管道问题 [英] OrderBy pipe issue
问题描述
我无法将此代码从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 Todo
s, 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
参数是什么?什么是a
和b
以及它们来自何处?
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屋!