[FIXED] How to use Date Pipes for some columns in PrimeNG table with dynamic number of columns

Issue

I am trying to display a dynamic number of columns, and also trying to use a <ng-template ... to specify how a cell is being rendered.But in my data set there are some fields belongs to date type. I want to format that fields using a date pipe.

html file

<ng-template pTemplate="body" let-rowData let-columns="columns">
      <tr>
        <td *ngFor="let col of columns" [style.width]="col.width">
          {{rowData[col.field]| col?.pipe}}
        </td>
      </tr>
</ng-template>

typescript file (In the cols array, I would like to add another field like this.)

 this.cols = [
      { field: 'no', header: 'No.', width: '50px',pipe:null },
      { field: 'createdDate', header: 'createdDate', width: '175px', pipe: 'date: \'dd/MM/yyyy\''},
      { field: 'deviceName', header: 'Device Name', width: '150px'}
    ];

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

ERROR Error: Uncaught (in promise): Error: Template parse errors:

Solution

Try like this

this.cols = [
          { field: 'no', header: 'No.', width: '50px',pipe:null },
          { field: 'createdDate', header: 'createdDate', width: '175px', data: true , format: `dd/MM/yyyy`},
          { field: 'deviceName', header: 'Device Name', width: '150px'}
        ];

template

<ng-template pTemplate="body" let-rowData let-columns="columns">
      <tr>
        <td *ngFor="let col of columns" [style.width]="col.width">   
          {{ col.data ? (rowData[col.field]| date : col.format) : rowData[col.field] }}
        </td>
      </tr>
</ng-template>

demo 🚀🚀

Answered By – Muhammed Albarmavi

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published