Search code examples
angularstring-interpolation

How to interpolate the current value of a variable in Angular?


I have this code in my ts file:

currentDate;
get_current_date() {
  this.currentDate = formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss', 'en');
}

And this in my HTML inside an ngFor directive:

<span class="hist-time">
  {{ currentDate }}
</span>

How do I get the current value of currentDate so that currentDate will display distinct dates and not the same date every time it updates?

Example:

2019-12-02 13:06:01
2019-12-02 13:06:13
2019-12-02 13:06:26
2019-12-02 13:06:51

and not:

2019-12-02 13:06:01
2019-12-02 13:06:01
2019-12-02 13:06:01
2019-12-02 13:06:01

Solution

  • You can add the current time to an array after regular interval.

    Try like this:

    Working Demo

    .ts

    import { interval } from "rxjs";

    currentTime = [];
    
    constructor() {
       this.currentTime.push(new Date());
       interval(10000).subscribe(x => {
         this.currentTime.push(new Date());        
       });
    }
    

    .html

    <p *ngFor="let time of currentTime"> 
         {{ time | date: 'yyyy-MM-dd HH:mm:ss' }}
    </p>