[英]How can I display date and time in Angular template and keep it updated?
我需要在我的 angular 模板中显示日期和时间,并保持更新,所以当时间更改为显示更改的时间时,应用程序应该如下所示:
这是我的 .html 模板代码:
<div class="top-right pull-right">
<button type="button" class="btn xbutton-rectangle" (click)="logOut()">
<div class="icon-user pull-left">
<i class="fas fa-user fa-fw"></i>
<span class="button-text">{{employee.FullName}}</span>
</div>
<div class="time-date pull-right">
<p class="button-time">08:55</p>
<p class="button-date">22.06.2018</p>
</div>
</button>
</div>
我的.ts
文件:
@Component({
selector: 'main-screen',
templateUrl: './main-screen.component.html',
styleUrls: ['./main-screen.component.css']
})
export class MainScreenComponent implements OnInit {
constructor() {
}
ngOnInit() {
//.. some methods
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
logOut() {
this._globals.isAuthenticated = false;
this._globals.loggedInUser = null;
this._globals.token = null;
}
}
那么如何显示日期和时间呢? 并在系统日期和时间更改时保持更新?
您需要做的就是在构造函数上使用 setInterval
date:Date;
constructor(){
setInterval(() => {
this.date = new Date()
}, 1000)
}
并使用日期管道格式化日期和时间
{{date | date: "mm-dd-yyyy"}}
{{date | date: "HH:mm:ss"}}
例如,您应该为日期分配一个变量并每 0.1 秒更新一次
public today = Date.now();
setInterval(() => {
this.today = Date.now();
}, 100);
如果你想要小时和分钟,你可以像这样在你的 html 中显示它,例如:
{{today | date:'HH:mm' }}
查看https://angular.io/api/common/DatePipe了解其他日期格式
只需像这样在您的组件中添加新功能
@Component({
selector: 'main-screen',
templateUrl: './main-screen.component.html',
styleUrls: ['./main-screen.component.css']
})
export class MainScreenComponent implements OnInit {
constructor() {
}
ngOnInit() {
this.utcTime();
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
utcTime(): void {
setInterval(function() {
this.myDate = new Date();
console.log(this.myDate); // just testing if it is working
}, 1000);
}
logOut() {
this._globals.isAuthenticated = false;
this._globals.loggedInUser = null;
this._globals.token = null;
}
然后使用角度日期管道根据需要更改日期格式
对我来说最简单的方法是直接在 HTML 中完成。 只需将此添加到您的 HTML
<script>document.write(new Date().getFullYear());</script>
因为我喜欢 RxJS,所以我使用它创建了一个服务,使用以下代码创建一个 ClockService:
import { Injectable } from '@angular/core';
import { interval, Observable, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ClockService {
constructor() { }
getClock() : Observable<Date> {
return interval(1000).pipe(
mergeMap(() => of(new Date()))
)
}
}
并在您的 component.ts 文件中注入您的服务,如下所示:
export class AppComponent implements OnInit {
clock: Observable<Date>;
constructor(private clockService: ClockService) { }
ngOnInit(): void {
this.clock = this.clockService.getClock();
}
}
最后,在您的 html 中使用它,您可以根据需要从Angular DatePipe 文档中调整日期过滤器:
{{ clock | async | date:'HH:mm:ss'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.