我认为您需要的信息一Component
不是Pipe
或Directive
。
此组件应该做你想要什么:
import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy } from '@angular/core';
@Component({
selector: 'ngx-countdown',
template: '{{ displayTime }}',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CountdownComponent implements OnDestroy {
private _time: number;
private _timing: number = 1000;
private _interval;
@Input()
public set time(value: string | number) {
this._time = parseInt(value as string, 10);
this._startTimer();
}
@Input()
public set timing(value: string | number) {
this._timing = parseInt(value as string, 10);
this._startTimer();
}
@Input()
public format: string = '{dd} days {hh} hours {mm} minutes {ss} seconds';
public get delta() {
let date = new Date();
return Math.max(0, Math.floor((this._time - date.getTime())/1000));
}
public get displayTime() {
let days, hours, minutes, seconds, delta = this.delta, time = this.format;
days = Math.floor(delta/86400);
delta -= days * 86400;
hours = Math.floor(delta/3600) % 24;
delta -= hours * 3600;
minutes = Math.floor(delta/60) % 60;
delta -= minutes * 60;
seconds = delta % 60;
time = time.replace('{dd}', days);
time = time.replace('{hh}', hours);
time = time.replace('{mm}', minutes);
time = time.replace('{ss}', seconds);
return time;
}
constructor(private _changeDetector: ChangeDetectorRef) { }
ngOnDestroy() {
this._stopTimer();
}
private _startTimer() {
if(this.delta <= 0) return;
this._stopTimer();
this._interval = setInterval(() => {
this._changeDetector.detectChanges();
if(this.delta <= 0) {
this._stopTimer();
}
}, this._timing);
}
private _stopTimer() {
clearInterval(this._interval);
this._interval = undefined;
}
}
你可以输入你要计算为unix时间戳,并定义应显示倒计时的格式的时间。
以下是使用上述组件的example。
谢谢!但即时通讯离开当前视图后(因为订阅的所有内容都被删除),即时通讯在倒计时出现错误。我怎么能毁掉所有不存在的倒计时?由于detectChanges – maria
更新了代码并添加了一个ngOnDestroy生命周期挂钩,该挂钩在组件销毁时停止定时器。 – cyrix