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

问题描述 投票:0回答:2

我的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
angular string-interpolation
2个回答
0
投票

您的代码应该可以正常工作,但是您是否曾经在代码中的任何地方调用get_current_date()来更新currentDate值?


0
投票

尝试这样:

Working Demo

。ts

  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>
© www.soinside.com 2019 - 2024. All rights reserved.