Search code examples
angulartypescriptmat-tabledate-pipe

Applying Date Pipe on Dynamic Angular Table


My "data" object looks like

[
 {"id": "abc001", "lastInspectionDate": "2019-09-26T00:00:00.000Z", "nextInspectionDate": "2021-09-26T00:00:00.000Z"},
 {"id": "abc002", "lastInspectionDate":"2018-08-25T00:00:00.000Z",  "nextInspectionDate": "2020-08-25T00:00:00.000Z"}
]

I want to display the data in a dynamic table. Below are my HTML code.

<table mat-table [dataSource]="dataSource" class="mt-2 mat-elevation-z0">
   <ng-container *ngFor="let column of allCols" [matColumnDef]="column">
      <th mat-header-cell *matHeaderCellDef>{{ column }}</th>
      <td mat-cell *matCellDef="let row">
         {{ column['lastInspectionDate'] ? (row[column]| date: 'mediumDate') : row[column] }}
      </td>
    </ng-container>
</table>

This is my ts codes where I define the dataSource for the table.

this.dataSource.data = data;
this.pageSize = data.length;
let headers = Object.keys(data[0]);
this.allCols = headers;

My conditional pipe for the date is not working. Can you guys help me or give me another kind of solution? I've been stucked at this for a week. Really appreciate your help.


Solution

  • Maybe you should try this :

    <table mat-table [dataSource]="dataSource" class="mt-2 mat-elevation-z0">
       <ng-container *ngFor="let column of allCols" [matColumnDef]="column">
          <th mat-header-cell *matHeaderCellDef>{{ column }}</th>
          <td mat-cell *matCellDef="let row">
             {{ column === 'lastInspectionDate' ? (row[column]| date: 'mediumDate') : row[column] }}
          </td>
        </ng-container>
    </table>