Angular 2排序表列

时间:2017-07-23 18:18:26

标签: javascript angular typescript

我正在尝试使用Angular 2

对表格列进行排序

管道转换代码是

(<tr class="hl" >)(.|\n)*?<\/tr>

我在component.ts文件中定义了一个sort函数,如下所示:

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;
      }
    });
  };
}

HTML看起来像这样

  sort(property){
    this.isDesc = !this.isDesc; //change the direction
    this.column = property;
    this.direction = this.isDesc ? 1 : -1;
    //this.sort(this.column);
  };

但加载页面后,我收到以下错误

zone.js:522未处理的承诺拒绝:./FundingRequestComponent类中的错误FundingRequestComponent - 内联模板:208:14导致:无法读取属性&#39; sort&#39;未定义的;区域:角;任务:Promise.then;值:     ViewWrappedError {__zone_symbol__error:错误:./FundingRequestComponent类中的错误FundingRequestComponent - 内联模板:208:14注意......}      错误:./FundingRequestComponent类中的错误FundingRequestComponent - 内联模板:208:14导致:无法读取属性&#39; sort&#39;未定义的         在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

1 个答案:

答案 0 :(得分:1)

我假设您在组件的类中异步加载此模板的数据(selectedData),因此一开始它尚未从服务中返回,因此{{1 }}

您可以采取以下措施来缓解这种情况:

1。初始化组件

中的数据

selectedData = undefined类属性设置为空数组,这样当管道运行时,即使后端数据尚未返回,其输入也将是一个数组。

selectedData

2。使用export class MyComponent { selectedData = []; }

阻止评估模板的这一部分

在您拥有阵列之前,不要使用所述管道渲染模板部件。

*ngIf

3。使管道&#34;空输入安全&#34;通过提供默认输入

这应该是首选解决方案,因为您不必记住使用任何特殊逻辑(例如 ver.1 ver.2 )每次你在某个地方使用这个管道。

<table *ngIf="selectedData">
  <!-- ... -->
  <tr *ngFor="let x of selectedData  | orderBy: {property: column, direction: direction}">
</table>

查看@Pipe({ name: 'orderBy' }) export class OrderByPipe implements PipeTransform { transform(records: Array<any> = [], args?: any): any { /* ... */ 方法参数中的records = []默认值?

我尝试将此作为一般经验法则用于始终准备管道以便最初无法输入。让很多头痛消失:)

相关问题