如何在 Angular 中插入变量的当前值?

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

我的 ts 文件中有这段代码:

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

这在我的 HTML 中的一个 ngFor 指令中:

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

如何获取 currentDate 的当前值,以便 currentDate 每次更新时显示不同的日期而不是相同的日期?

示例:

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

而不是:

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

您可以在固定时间间隔后将当前时间添加到数组中。

这样试试:

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>

@Adrita Sharma 的修改版本post,以防您不想打印所有值

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>