Wir*_*Xie 3 sorting html-table pipe typescript angular
我正在尝试按照此链接为表创建排序函数和管道,这是该示例的plunker。从我跟随表标题的示例来看,应该是可点击的并执行该sort()功能。我的管道名称是prdSort. 我也在使用,ngx-pagination但我认为这不是此错误的主要原因。
//part of service.ts
productList: AngularFireList < any > ;
//end
//component.ts
productList: Product[];
isDesc: boolean = false;
column: string = 'prdName';
records = this.productList
sort(property) {
this.isDesc = !this.isDesc; //change the direction
this.column = property;
let direction = this.isDesc ? 1 : -1;
};Run Code Online (Sandbox Code Playgroud)
<!-- table header -->
<th (click)="sort('prdName')">Name</th>
<!--table row-->
<tr *ngFor="let product of productList | paginate: { itemsPerPage: 3, currentPage: p } | prdSort: {property: column, direction: direction} ">Run Code Online (Sandbox Code Playgroud)
//pipe.ts
transform(records: any, args ? : any): any {
return records.sort(function(a, b) {
if (records !== undefined) {
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;
}
}
return records;
});
};Run Code Online (Sandbox Code Playgroud)
我也已经将管道文件包含到app.module.ts. 如果需要更多片段,请告诉我。
尝试使用空数组初始化您的 productList:
// component.ts:
productList: Product[] = [];
Run Code Online (Sandbox Code Playgroud)
为了提高安全性,为了防止对未定义的变量而不是数组调用array.prototype.sort,您可以在过滤器中添加以下代码:
transform(records: any, args ? : any): any {
records = records || []; // set records to an empty array if undefined
return records.sort(function(a, b) { ... });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17816 次 |
| 最近记录: |