我需要一个可用的 Angular 4 数字时钟
尝试使用正常的 javascript 和 setInterval 使其每 60 秒运行一次函数。但字符串插值不会更新属性更改时的时间。
theDate = new Date();
theDay = this.theDate.getDay();
hours = this.theDate.getHours();
minutes = this.theDate.getMinutes();
session = "AM";
ngOnInit() {
if (this.hours == 0) {
this.hours = 12;
}
if (this.hours > 12) {
this.hours = this.hours - 12;
this.session = "PM";
}
this.stringHours = (this.hours < 10) ? "0" + this.hours : this.hours;
this.stringMinutes = (this.minutes < 10) ? "0" + this.minutes : this.minutes;
this.clock = this.stringHours + ":" + this.stringMinutes + " " + this.session;
this.refreshClock();
}
refreshClock() {
setInterval(() => {
this.hours = this.theDate.getHours();
this.minutes = this.theDate.getMinutes();
this.stringHours = (this.hours < 10) ? "0" + this.hours : this.hours;
this.stringMinutes = (this.minutes < 10) ? "0" + this.minutes : this.minutes;
this.clock = this.stringHours + ":" + this.stringMinutes + " " + this.session;
console.log('work');
}, 1000)
}
所以我尝试了 Angular 日期管道,但它也没有更新时间,只是在刷新应用程序后刷新它。
typescript
theDate = new Date();
HTML
{{ theDate | date :'shortTime' }}
Angular 日期管:
https://angular.io/api/common/DatePipe
最佳答案
您错过了更新 setInterval()
内的 theDate
refreshClock() {
setInterval(() => {
this.hours = this.theDate.getHours();
this.minutes = this.theDate.getMinutes();
this.stringHours = (this.hours < 10) ? "0" + this.hours : this.hours;
this.stringMinutes = (this.minutes < 10) ? "0" + this.minutes : this.minutes;
this.clock = this.stringHours + ":" + this.stringMinutes + " " + this.session;
console.log('work');
// add this line
this.theDate = newly calculated date
}, 1000)
}
关于javascript - Angular 4 日期管道短时间格式,每分钟更新一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50679150/