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 的响应,以便管道可以在 angular 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'"
希望这对某人有所帮助.
Hopefully this helps someone.
这篇关于OrderBy 管道问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!