Search code examples
angularintervalsangular9timing

What's the Angular way to update my cell timing data every minute?


I have this in my Angular 9, mat-table. This cell is supposed to display how long ago an item was created ...

<ng-container matColumnDef="date">
  <mat-header-cell *matHeaderCellDef> Posted on </mat-header-cell>
  <mat-cell *matCellDef="let item">{{ getCreatedOn(item) }} ago</mat-cell>
</ng-container>

In the ts file, the function I use looks like this

  getCreatedOn(item: Item): string {
    const timeSince = (new Date()).getTime() - item.created_on_ms;
    return this.getTimeUnitAsStr(timeSince);
  }

The issue is this data is static. That is, when the page first loads it may read "37 minutes ago", but for every subsequent minute, I'd like the data to update to show "38 minutes ago", "39 minutes ago", and so on. What's the proper Angular way to update this particular piece of data every minute?


Solution

  • The most faster way is to use ngx-moment to use the time ago pipe

    Please install ngx-moment then use pipe in this way

    <ng-container matColumnDef="date">
      <mat-header-cell *matHeaderCellDef> Posted on </mat-header-cell>
      <mat-cell *matCellDef="let item">{{ item.created_on_ms | amTimeAgo }} ago</mat-cell>
    </ng-container>