1

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

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking of a way where there's no memory required, somewhat like just printing. But this works. Thanks!
0

Modified version of @Adrita Sharma post, in case if you don't want to print all values

import { interval, Observable, of } from "rxjs";

currentTime: Observable<Date>;

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

**HTML**
<p>{{currentTime | async | date: 'yyyy-MM-dd HH:mm:ss' }}</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.