Diego Unanue Diego Unanue - 11 days ago 5
Javascript Question

Time CountDown in angular 2

I want to have a date countdown like this:

http://codepen.io/garethdweaver/pen/eNpWBb

but in angular 2, I found this plunkr that adds 1 to a number each 500 miliseconds:

https://plnkr.co/edit/pVMEbbGSzMwSBS4XEXJI?p=preview

this is the code:

import {Component,Input} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
selector: 'my-app',
template: `
<div>
{{message}}
</div>
`
})
export class AppComponent {

constructor() {
Observable.interval(1000)
.map((x) => x+1)
.subscribe((x) => {
this.message = x;
}):
}
}


But I want to have a date taking one second until reach 0.

Answer
import {Component, NgOnInit, ElementRef} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
selector: 'my-app',
template: `
  <div>
    {{message}}
  </div>
`
})
export class AppComponent implements OnInit {

  private future:Date;
  private futureString:string;
  private diff:Date;

    constructor(elm: ElementRef) {
        this.futureString = elm.nativeElement.getAttribute('inputDate'); 
    }

  dhms(t){
     var days, hours, minutes, seconds;
     days = Math.floor(t / 86400);
     t -= days * 86400;
     hours = Math.floor(t / 3600) % 24;
     t -= hours * 3600;
     minutes = Math.floor(t / 60) % 60;
     t -= minutes * 60;
     seconds = t % 60;

     return [
             days + 'd',
             hours + 'h',
             minutes + 'm',
             seconds + 's'
            ].join(' ');                              
  }


   ngOnInit() {
     this.future = new Date(this.futureString);
       Observable.interval(1000).map((x) => {
        this.diff = Math.floor((this.future.getTime() - new Date().getTime()) / 1000);
    }).subscribe((x) => { 
            this.message = this.dhms(this.diff);
          });
  }
}

HTML:

 <my-app inputDate="January 1, 2017 12:00:00">Loading...</my-app>
Comments