Angular PrimeNG table set up pipe per column using cols array
Asked Answered
W

1

3

I am trying to learn angular with PrimeNG. Here is the link https://primefaces.org/primeng/#/table.

Is it possible to also include the pipe for each column using the pipe array?

In the cols array, I would like to add another field like this.

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

And then in the template, I would use it like this

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

I've tried this and it gives me template parsing errors.

Widower answered 20/6, 2018 at 9:19 Comment(0)
E
9

You can try to do following:

  1. In your ts file import pipes that you need:

    import { 
      CurrencyPipe,
      LowerCasePipe,
      UpperCasePipe
    } from '@angular/common';
    
  2. Add them to providers property of your component

    providers: [
      CurrencyPipe, 
      LowerCasePipe,
      UpperCasePipe
    ]
    
  3. Pass pipes via constructor as private

    constructor(private cp: CurrencyPipe, 
                private lcp: LowerCasePipe,
                private ucp: UpperCasePipe) {
    }
    
  4. Pass pipes to your HTML via cols:

    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' }
    ];
    

    I did not find a nice way to pass an array of args to HTML (pipe(val, ...args) will not work in HTML), so I added arg1, arg2 and arg3, which we can pass and use.

  5. Consume it in your 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 example: https://stackblitz.com/edit/angular-4x6q9b?file=app%2Fapp.module.ts

Exposition answered 20/6, 2018 at 12:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.