I'm looking to create angular 2/4 countdown pipe.
Of course I can make individual countdowns, but how do I create multiple ones?
I want the following input:
<span [time]="unix timestamp here">Countdown will count here</span>
for example:
<span [time]="1500503492">Countdown will count here</span>
<span [time]="15005034392">Countdown will count here</span>
<span [time]="1500503492">Countdown will count here</span>
How can I achieve that all would work no matter how many I have?
What I tried so far is only single countdowns like the following:
time = 30;
setInterval(() => {
this.currentTime = new Date().getTime();
if (this.time > 0) {
this.time = this.time - 1;
}
}, 1000);
{{ time}}
I think your're looking for a Component
not a Pipe
or Directive
.
This component should do what you want:
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;
}
}
You can input the time you want to count to as unix timestamp and also define a format in which the countdown should be displayed.
Here's an example using the above component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With