Please help with counter component

Hi,

recently I developed a Angular 2 component which shows a time counter like this:

image

This counter works fine using:

<count-up></count-up>

My component code is this:

What I need now is to pass an initial time (in miliseconds) to my count-up controller. Something like this:

<count-up initial="{{initialTime}}"></count-up>

or

<count-up initial="340000"></count-up>

I’ve been trying using @Input and @Attribute with no success. :frowning2:

Can anyone help me to implement this feature?

Thanks in advance.

@Input(‘initial’) milisegons: number;

hi @ramon,

you can access @input values After component being initialized. ( In ngOnInit or ngAfterContentInit )

 @Component({
     selector: 'count-up',
     template: '{{ time_str }}',
     inputs: ['initial']
 });
 export class CountUp {
      initial: number;

      ngOnInit() {
          this.time_str = this.convertTime(parseInt(this.initial));
     }
 }

Thanks @itsmemyk !

Your solution seems to work:

<count-up initial="{{initialTime}}"></count-up>

This is my new ‘countup.component.ts’ file:

import {Component} from "angular2/core";

@Component({
    selector: 'count-up',
    template: '{{time_str}}',
    inputs: ['initial']
})

export class CountUp {
    miliseconds: number = 0;
    time_str: string;
    initial: string;

    ngOnInit() {
        this.miliseconds = parseInt(this.initial);
        this.time_str = this.convertTime(this.miliseconds);
    }

    constructor() {
        setInterval(()=>{
            this.miliseconds = this.miliseconds + 1000;
            this.time_str = this.convertTime(this.miliseconds);
        }, 1000);
    }

    /**
     * Converts miliseconds to 'hh:mm:ss' string
     *
     * @param {number} miliseconds
     * @returns {string}
     */
    convertTime (miliseconds:  number) {
        let sec: number = miliseconds / 1000;
        let hours, minutes, seconds: number;
        let hours_str, minutes_str, seconds_str: string;

        hours = Math.floor(((sec % 31536000) % 86400) / 3600);
        hours_str = (hours <=9) ? '0' + hours.toString() : hours.toString() ;

        minutes = Math.floor((((sec % 31536000) % 86400) % 3600) / 60);
        minutes_str = (minutes <=9) ? '0' + minutes.toString() : minutes.toString() ;

        seconds = Math.floor(((sec % 31536000) % 86400) % 3600) % 60;
        seconds_str = (seconds <=9) ? '0' + seconds.toString() : seconds.toString() ;

        return hours_str +':'+ minutes_str +':'+ seconds_str;
    }

}

Thanks for you reply @xr0master!

Later, I’ll try your solution too.