This question already has answers here:
How to access the correct `this` inside a callback (13 answers)
Closed 3 years ago.
I am new in javascript and angular. This should be a simple issue but I don't know what is wrong with my code. I don't know if i have the proper syntax for the time handler. The code just display the time only once.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello-world',
templateUrl: './hello-world.component.html',
styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent implements OnInit {
dateMessage: string;
constructor() {
setInterval(this.time_handler, 1000);
//Method 1: This works
// setInterval(()=> {
// let currentDate = new Date();
// this.dateMessage = currentDate.toLocaleTimeString();
// }, 1000);
}
ngOnInit() {
}
// Method 2: This does not work
public time_handler() {
let currentDate = new Date();
this.dateMessage = currentDate.toLocaleTimeString();
}
}
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)