Danzeeeee Danzeeeee - 1 year ago 187
TypeScript Question

Angular 2 "this" unable to access global variable in nested function

I'm quite new to Angular 2. Would like to ask how can I access "task_title" in the startTimer().
All I got from the console.log() is undefined. I believe the "this" was pointing to the function itself so I couldn't get the value of "task_title".

Is there anyway I can access to global variable in Typescript in a nested function?

export class DashboardComponent {

task_title: string;

myTimer = setTimeout(this.startTimer, 2000);

updateTask(event: any){
this.task_title = event.target.value;
this.myTimer = setTimeout(this.startTimer, 2000);

startTimer() {
this.myTimer = setTimeout(this.startTimer, 2000);

Result: Undefined.

Answer Source

Use arrow functions or .bind(this) to retain the scope of this

myTimer = setTimeout(this.startTimer.bind(this), 2000);
myTimer = setTimeout(() => this.startTimer(), 2000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download