Monday, May 21, 2018

javascript - Angular 2 - Using 'this' inside setTimeout




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.


Answer



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);

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...