I’m calling a C# API that’s returning the following types to my Angular application.
export interface Auction {
reservePrice: number
currentHighBid: number
auctionEnd: string
id: string
}
I created an AuctionListComponent that will ngFor
a list of auction to the screen and in the list I want to add a countdown timers. So I created another component for that called TimerComponent. The parent component is passing a UTC string date to the child. The child timer component needs a type of number for the ngx-countdown timer to work. I’m no pro at Angular so am I missing something simple here?
I’ve also looked over this similar questions as well and didn’t help me.
similar question
(Parent) AuctionListComponent.html
<div class="m-3" *ngFor="let auction of auctions">
<p class="card-text">
End Date: {{ auction.auctionEnd | date }}
</p>
<app-timer [childTimer]="auction.auctionEnd"></app-timer>
</div>
(Child) TimerComponent.html
<p>
From the parent: <b>{{ childTimer | date : 'MM d, y, h:mm:ss a' }}</b>
UTC: <b>{{ childTimer }}</b>
</p>
<p>ngx-countdown Counter</p>
<countdown [config]="config"> </countdown>
TimerComponent.TS
import { Component, Input } from '@angular/core';
import { CountdownConfig, CountdownEvent } from 'ngx-countdown';
@Component({
selector: 'app-timer',
templateUrl: './timer.component.html',
styleUrl: './timer.component.scss'
})
export class TimerComponent {
@Input() childTimer: string = ''; //This doesn't work because it's the wrong type
@Input() childTimer: any; //This compiles and give an error
//ERROR Error: Unable to convert "Invalid Date" into a date
config: CountdownConfig = { leftTime: this.childTimer, format: 'd:H:M:ss'};
}
2
Answers
According to the ngx-countdown documentation, the leftTime parameter must be a number.
So if you convert childTimer to number, by instantiating the config variable, it should work correctly.
ngx-countdown
expectsleftTime
to be a number representing seconds left. So to make it work you need to find a difference betweenauctionEnd
which is a UTC string and the current Date and convert it into seconds.Here is how your component could do this:
Update
I digged into documentation of
ngx-countdown
and there isstopTime
option in the config that makes it even simpler as it accepts "end time" as timestamp, so the example could be simplified to: