title: Angular2 prevent destroying a Component on route change
body: <p>I use <a href="https://github.com/NathanWalker/angular-seed-advanced" rel="nofollow noreferrer">angular-seed</a> template for my angular2 app. And I wrote a simple stopwatch. If i start the timer and change the route, the component will be destroyed and the timer stops. How can I prevent this? The timer should work in the background.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import {Component, ElementRef} from "@angular/core";
  import {WindowService} from "../services/window.service";
  
  @Component({
      selector: 'timer',
      template: `&lt;div&gt;
                  &lt;span&gt;0&lt;/span&gt;&lt;br&gt;
                  &lt;button (click)="start()"&gt;start&lt;/button&gt;
                  &lt;button (click)="stop()"&gt;stop&lt;/button&gt;
                  &lt;/div&gt;`
  })
  
  export class TimerDirective {
  
      private running:boolean;
      private time:number;
      private results:Array&lt;any&gt;;
      private laps:Array&lt;string&gt;;
      private times:Array&lt;number&gt;;
      private win:any;
      private timeEnd:any;
  
  
      constructor(private el: ElementRef, private winA: WindowService) {
          console.log("time");
  
          this.running = false;
          this.time = -1;
          this.results = [];
          this.laps = [];
          this.times = [0, 0, 0];
          this.win = window;
          this.timeEnd = performance;
  
      }
  
      ngOnDestroy() {
          this.winA.alert("no please");
      }
      public reset() {
          this.times = [0,0,0];
      }
  
      public stop() {
          this.running = false;
          this.time = -1;
      }
  
      public start() {
          if(this.time === -1) {
              this.time = this.timeEnd.now();
          }
           if(this.running == false) {
  
              this.running = true;
              requestAnimationFrame(this.step.bind(this));
          }
      }
  
      public step(timestamp:any) {
          if(this.running == false) {
              return;
          }
          this.calculate(timestamp);
          this.time = timestamp;
          this.print();
          requestAnimationFrame(this.step.bind(this));
      }
  
      public calculate(timestamp:any) {
          let diff = timestamp - this.time;
  
          this.times[2] += diff / 10;
  
          if (this.times[2] &gt;= 100) {
              this.times[1] += 1;
              this.times[2] -= 100;
          }
  
          if (this.times[1] &gt;= 60) {
              this.times[0] += 1;
              this.times[1] -= 60;
          }
      }
  
      public print() {
          let elSpan = this.el.nativeElement.querySelector('span');
          elSpan.innerHTML = this.times;
  
      }
  }</code></pre>
  </div>
  </div>
  </p>