gpt4 book ai didi

javascript - Angular 2多重倒计时管道

转载 作者:数据小太阳 更新时间:2023-10-29 04:36:02 26 4
gpt4 key购买 nike

我正在寻找 Angular 2/4 倒计时管道。

当然我可以单独倒计时,但如何创建多个倒计时?

我想要以下输入:

<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}}

最佳答案

我认为您要查找的是 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使用上述组件。

关于javascript - Angular 2多重倒计时管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45203114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com