1

请问如何刷新日期angular 4

我需要在网页中动态显示日期。

这是我的代码:

import { Component } from '@angular/core';

import * as moment from "moment";

 @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
 })
 export class AppComponent {
      title = 'My First Angular application';
      oneHourAgo: string = "";
      EightHoursAgo: string = "";
      constructor(  ) { 

  }

  curTime() {
         let now = moment().format("YYYY-MM-DD HH:mm:ss");
         return now;
  }    

}
4

1 回答 1

1

只需将结果绑定到模板,如下所示:

export class AppComponent implements OnInit, OnDestroy {
  myTime
  myInterval
  title = 'My First Angular application';
  oneHourAgo: string = "";
  EightHoursAgo: string = "";
  constructor () {}

  // you may want to use ngOnInit to call curTime   
  ngOnInit() {
    this.curTime()
    this.myInterval = setInterval(() => {
      this.curTime()
    }, 1000)
  }

  // if using setInterval then be sure to clean up else it will keep
  // firing after the component is destroyed
  ngOnDestory() {
    clearInterval(this.myInterval)
  }

  curTime() {
     console.log('hello i am updating the displayed time')
     this.myTime = moment().format("YYYY-MM-DD HH:mm:ss");
  }
}

在组件的 HTML 模板中:

<div>{{ myTime }}</div>

无论您做什么,都要确保 curTime() 被调用。我想你是在 HTML 中调用它。

于 2019-03-29T11:18:31.370 回答