In this basic app.component.ts sample snippet (created only for learning purposes), I've observed that if I use a setInterval block in the constructor, string-interpolating a template variable from that block is not gonna work.
I know this is not a meaningful example but it does show the issue:
What technique should be used here so we can update {{ timeDisplay }} area in the template?
This looks like a scope issue. Can this be solved thru a global variable? Or what's a better way to tackle this capability?
import { Component, OnInit } from '@angular/core';
export class Hero {
id: number;
name: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
timeDisplay: string;
constructor () {
this.timeDisplay = 'time will be displayed right here.';
// set timer
setInterval(
function(){
this.timeDisplay = new Date(); // this does not create an error but does not do anything neither. it is most likely timeDisplay variable is not in the constructor's scope
},
1000
);
}