186

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.

1
  • 1
    I believe this is not a duplicate, the this clause in angular is different from normal javascript. (gets converted to _this in the final code) Commented Aug 29, 2018 at 0:05

1 Answer 1

484

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);
Sign up to request clarification or add additional context in comments.

7 Comments

It always works. There could be some other problem. i'd like you to investigate it or you can ask a relevant question @RomainBruckert
thats a great answer!! Thanks, solved a big problem. By the way can you please suggest where else do we need to use ()=> in angular 7?
@sid: That is ES6/ES7 standard. If you use typescript, it is used everywhere.
ok so everytime i use angular7/typescript, i have to use () => right?
Does not work in angular/typescript.... still have to store the outer scope in a variable...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.