【发布时间】:2017-07-24 06:01:17
【问题描述】:
我正在尝试使用 Angular 2 对表格中的列进行排序
管道变换代码是
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'orderBy' })
export class OrderByPipe 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;
}
});
};
}
我在component.ts文件中定义了一个排序函数,如下:
sort(property){
this.isDesc = !this.isDesc; //change the direction
this.column = property;
this.direction = this.isDesc ? 1 : -1;
//this.sort(this.column);
};
HTML 看起来像这样
<th class="cell-width-header title" (click)="sort(sellerNo)">
Seller No
<i class="fa" [ngClass]="{'fa-sort': column != 'sellerNo', 'fa-sort-asc': (column == 'sellerNo' && isDesc), 'fa-sort-desc': (column == 'sellerNo' && !isDesc) }" aria-hidden="true"> </i>
</th>
<tr *ngFor="let x of selectedData | orderBy: {property: column, direction: direction}">
<td>{{x.sellerNo}}</td>
但在加载页面后,我收到以下错误
zone.js:522 未处理的承诺拒绝:./FundingRequestComponent 类 FundingRequestComponent 中的错误 - 内联模板:208:14 原因:无法读取未定义的属性“排序”;区域:角度;任务:Promise.then;价值: ViewWrappedError {__zone_symbol__error: Error: Error in ./FundingRequestComponent class FundingRequestComponent - inline template:208:14 cau……} 错误:./FundingRequestComponent 类 FundingRequestComponent 中的错误 - 内联模板:208:14 原因:无法读取未定义的属性“排序” 在 ViewWrappedError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:6688:33) 在 ViewWrappedError.BaseError [作为构造函数] (http://localhost:4200/vendor.bundle.js:94913:16) 在 ViewWrappedError.WrappedError [作为构造函数] (http://localhost:4200/vendor.bundle.js:94978:16) 在新的 ViewWrappedError (http://localhost:4200/vendor.bundle.js:96282:16)
【问题讨论】:
-
selectedData的类型是什么?
-
是 JSON,来自后端服务
-
什么是sellerNo? .ts 文件中的变量?如果没有,我想你想要的属性的名称是这样排序的。将其包裹在 ''
-
您在对象中调用 .sort 的唯一位置是在管道中。当您调用管道时,最有可能 selectedData 为空/未定义......
-
@Jota.Toledo Seller no 是列的名称,也是我正在过滤的 json 数据中的一个元素
标签: javascript angular typescript