我基于此示例对表的列进行排序: Sort Table Colums
这是代码管道:
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({ name: 'orderBy' })
export class OrderrByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
return records.sort(function(a, b){
if(a[args.property] < b[args.property]){
return -1 * args.direction;
}
else if( a[args.property] > b[args.property]){
return 1 * args.direction;
}
else{
return 0;
}
});
};
}
这是html代码:
<tr *ngFor="let particular of particulars | orderBy: {property: column, direction: direction} | slice:1; let i = index">
组件中的导入:
import { OrderrByPipe } from '../pipes/orderby.pipe';
我想将管道类迁移到Angular 4,怎么可能呢?
这是控制台中的错误:
error_handler.js:60 Error: Uncaught (in promise): Error: Error in ./ParticularsListComponent class ParticularsListComponent - inline template:42:14 caused by: Cannot read property 'sort' of undefined
Error: Error in ./ParticularsListComponent class ParticularsListComponent - inline template:42:14 caused by: Cannot read property 'sort' of undefined
答案 0 :(得分:2)
您的问题来自未定义的particulars
变量。
答案 1 :(得分:0)
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderby'
})
export class OrderbyPipe implements PipeTransform {
//private records : Array<any> = [];
transform(records :Array<Object>, args?: any): any {
if(records != null){
return records.sort(function(a, b){
if (a[args.property] === '' || a[args.property] === null || typeof a[args.property] === 'undefined') {
return 1 * args.direction;
}
if (b[args.property] === '' || b[args.property] === null || typeof b[args.property] === 'undefined') {
return -1 * args.direction;
}
if(a[args.property] < b[args.property]){
return -1 * args.direction;
}
else if( a[args.property] > b[args.property]){
return 1 * args.direction;
}
else{
return 0;
}
});
}
};
}