6

我正在尋找創建角度2/4倒計時管道。角度2多個倒計時管道

當然我可以單獨倒計時,但是如何創建多個倒計時?

我想下面的輸入:

<span [time]="unix timestamp here">Countdown will count here</span> 

例如:

<span [time]="1500503492">Countdown will count here</span> 
<span [time]="15005034392">Countdown will count here</span> 
<span [time]="1500503492">Countdown will count here</span> 

我如何能實現所有將工作無論我有多少?

我試過到目前爲止只有單一的倒計時類似如下:

time = 30; 
setInterval(() => { 
    this.currentTime = new Date().getTime(); 
    if (this.time > 0) { 
    this.time = this.time - 1; 
    } 
}, 1000); 

{{ time}} 

回答

4

我認爲您需要的信息一Component不是PipeDirective

此組件應該做你想要什麼:

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

+0

謝謝!但即時通訊離開當前視圖後(因爲訂閱的所有內容都被刪除),即時通訊在倒計時出現錯誤。我怎麼能毀掉所有不存在的倒計時?由於detectChanges – maria

+0

更新了代碼並添加了一個ngOnDestroy生命週期掛鉤,該掛鉤在組件銷燬時停止定時器。 – cyrix