请问如何在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;
}
}
只需将结果绑定到模板,如下所示:
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中调用它。