Angular 2 - Using 'this' inside setTimeout

JavascriptAngularScope

Javascript Problem Overview


I have a function like so in my class

  showMessageSuccess(){
    
    var that = this;
    this.messageSuccess = true;

    setTimeout(function(){
      that.messageSuccess = false;
    },3000);
  
  }

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.

Javascript Solutions


Solution 1 - Javascript

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2085143View Question on Stackoverflow
Solution 1 - JavascriptNikhil ShahView Answer on Stackoverflow