如何在Angular 4中刷新日期

问题描述 投票:1回答: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;
  }    

}
angular date refresh
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中调用它。

© www.soinside.com 2019 - 2024. All rights reserved.