Angular PrimeNG table 使用 cols 数组为每列设置管道

Angular PrimeNG table set up pipe per column using cols array

我正在尝试使用 PrimeNG 学习 angular。这里是linkhttps://primefaces.org/primeng/#/table

是否可以使用管道数组为每一列添加管道?

在 cols 数组中,我想像这样添加另一个字段。

this.cols = [
    { field: 'vin', header: 'Vin', type: 'date' },
    { field: 'year', header: 'Year', type: 'number' },
    { field: 'brand', header: 'Brand', type: 'number' },
    { field: 'color', header: 'Color'}
];

然后在模板中,我会这样使用它

<tr>
    <td *ngFor="let col of columns">
        {{ col.type? rowData[col.field] | col.type : rowData[col.field]}}
    </td>
</tr>

我已经试过了,它给我模板解析错误。

您可以尝试进行以下操作:

  1. 在你的ts文件中导入你需要的管道:

    import { 
      CurrencyPipe,
      LowerCasePipe,
      UpperCasePipe
    } from '@angular/common';
    
  2. 将它们添加到组件的提供者属性

    providers: [
      CurrencyPipe, 
      LowerCasePipe,
      UpperCasePipe
    ]
    
  3. 通过构造函数传递管道作为 private

    constructor(private cp: CurrencyPipe, 
                private lcp: LowerCasePipe,
                private ucp: UpperCasePipe) {
    }
    
  4. 通过 cols:

    将管道传递给您的 HTML
    this.cols = [
      { field: 'vin', header: 'Vin', type: this.ucp },
      { field: 'startYear', header: 'Year', type: this.cp, arg1: 'CAD'},
      { field: 'brand', header: 'Brand', type: this.lcp },
      { field: 'color', header: 'Color' }
    ];
    

    我没有找到将 args 数组传递给 HTML 的好方法(pipe(val, ...args) 在 HTML 中不起作用),所以我添加了 arg1arg2arg3,我们可以传递和使用。

  5. 在你的HTML中消费它:

    <td *ngFor="let col of columns">
      {{ col.type ? col.type.transform(rowData[col.field], col.arg1, col.arg2, col.arg3) : rowData[col.field] }}
    </td>
    

Stackblitz 示例:https://stackblitz.com/edit/angular-4x6q9b?file=app%2Fapp.module.ts