Timer countdown Angular 2

Try this for timer:

<h5><span id="time" class="text-primary">00:00</span></h5>

component.ts

import { Component, OnInit, ElementRef, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';

export class AppComponent implements OnInit {

    constructor(private elementRef: ElementRef) { }

    ngOnInit() {
        var callDuration = this.elementRef.nativeElement.querySelector('#time');
        this.startTimer(callDuration);
    }

    startTimer(display) {
        var timer = 1800;
        var minutes;
        var seconds;

        Observable.interval(1000).subscribe(x => {
            minutes = Math.floor(timer / 60);
            seconds = Math.floor(timer % 60);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.textContent = minutes + ":" + seconds;

            --timer;
            if (timer < 0) {
                 console.log('timer is ended');
            }
        })
    }
}

You can 'listen' to the timer and trigger the action when the countdown is 0. And to display the timer, use a pipe.

HTML

{{counter | formatTime}}    

TypeScript

  countDown:Subscription;
  counter = 1800;
  tick = 1000;
  ngOnInit() {
    this.countDown = timer(0, this.tick)
      .subscribe(() => --this.counter)
  }
  ngOnDestroy(){
    this.countDown=null;
  }

Pipe

//for MM:SS format
  transform(value: number): string {
    const minutes: number = Math.floor(value / 60);
    return ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);
  }

DEMO

//for HH:MM:SS format

transform(value: number): string {
    const hours: number = Math.floor(value / 3600);
    const minutes: number = Math.floor((value % 3600) / 60);
    return ('00' + hours).slice(-2) + ':' + ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);
}

DEMO


If you wish to use a service:

Service

 ...
  getCounter(tick) {
    return timer(0, tick) 
  }
 ...

Component

  countDown;
  counter=1800 ;
  tick=1000;

  constructor(private myService: MyService) {
  }

  ngOnInit() {
    this.countDown = this.myService.getCounter(this.tick).subscribe(() => this.counter--);

  }

  ngOnDestroy(){
    this.countDown=null;
  }

Pipe

  ...  
  transform(value: number): string {
    //MM:SS format
    const minutes: number = Math.floor(value / 60);
    return ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);

    // for HH:MM:SS
    //const hours: number = Math.floor(value / 3600);
    //const minutes: number = Math.floor((value % 3600) / 60);
    //return ('00' + hours).slice(-2) + ':' + ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2);

  }

DEMO