0

Anyone know why my variables aren't being displayed on my page? I'm creating a countdown timer, and the variables are being updated, but not displayed on my page. Not really sure what the problem is. It's console logging the days out every second like it should, but it's not displaying on my site when I have {{days}}

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-fireworks',
  templateUrl: './fireworks.component.html',
  styleUrls: ['./fireworks.component.scss']
})
export class FireworksComponent implements OnInit {
  public days;
  public hours;
  public minutes;
  public seconds;
  constructor() { }

  ngOnInit() {
  let time = new Date("July 4, 2020 00:00:00").getTime();
  let x = setInterval(function() {
    let now = new Date().getTime();

let distance = time - now;

this.days = Math.floor(distance / (1000 * 60 * 60 * 24));
this.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
this.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
this.seconds = Math.floor((distance % (1000 * 60)) / 1000);

console.log(this.days)

  if (distance < 0) {
    clearInterval(x);
  }
  }, 1000);
  }
}

Template:

<h1>test</h1>

<p>{{days}}</p>

1 Answers1

4

It's because you're declaring your callback function like this:

function() { }

instead of using arrow function notation:

() => { }

You need to convert your callback to be an arrow function.

let x = setInterval(() => {
  // ...
}, 1000);

This works because this inside an arrow function refers to the outer scope, whereas in a function() { } it refers to the function itself. At the moment all you are doing is setting properties on the inner function rather than the component.

Clear the interval in ngOnDestroy

As an aside, you will also want to clear the interval in ngOnDestroy() to ensure that the callback doesn't continue to run after the component has been destroyed.

You could also explore the RxJS interval function as an alternative.

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40