185

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)
    – aliqandil
    Commented Aug 29, 2018 at 0:05

1 Answer 1

480

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);
7
  • 2
    It always works. There could be some other problem. i'd like you to investigate it or you can ask a relevant question @RomainBruckert
    – micronyks
    Commented Aug 22, 2017 at 13:12
  • 1
    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
    Commented Jul 6, 2019 at 11:44
  • 1
    @sid: That is ES6/ES7 standard. If you use typescript, it is used everywhere.
    – micronyks
    Commented Jul 26, 2019 at 6:53
  • 1
    ok so everytime i use angular7/typescript, i have to use () => right?
    – sid
    Commented Jul 26, 2019 at 7:02
  • Does not work in angular/typescript.... still have to store the outer scope in a variable... Commented Feb 6, 2020 at 21:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.