Angular 2 – Using ‘this’ inside setTimeout [duplicate]

Angular 2 – Using ‘this’ inside setTimeout [duplicate]

This question already has an answer here:

How to access the correct `this` inside a callback?

10 answers

I have a function like so in my class

var that = this;
this.messageSuccess = true;

that.messageSuccess = false;


How can I re-write this so I don’t have to store a reference to ‘this’ in the ‘that’ var? If I use ‘this’ inside the setTimeout, the messageSuccess bool doesn’t seem to change/get updated.


Solution 1:

You need to use ArrowFunction ()=> to preserve this context within setTimeout.

// var that = this; // no need of this line
this.messageSuccess = true;

setTimeout(()=>{    //<<<---    using ()=> syntax
      this.messageSuccess = false;
 }, 3000);