183

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.

Roham Rafii
  • 2,929
  • 7
  • 35
  • 49
user2085143
  • 4,162
  • 7
  • 39
  • 68
  • 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 Aug 29 '18 at 00:05

1 Answers1

474

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);
Yuriy Yakym
  • 3,616
  • 17
  • 30
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • 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 Aug 22 '17 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 Jul 06 '19 at 11:44
  • 1
    @sid: That is ES6/ES7 standard. If you use typescript, it is used everywhere. – micronyks Jul 26 '19 at 06:53
  • 1
    ok so everytime i use angular7/typescript, i have to use () => right? – sid Jul 26 '19 at 07:02
  • Does not work in angular/typescript.... still have to store the outer scope in a variable... – Manuel Azar Feb 06 '20 at 21:40
  • Hi everyone, realy you can't call setTimeout out of any function, so, if you want to call you can put it on ngInit() hook – Higor Tavares Apr 05 '21 at 19:25
  • Also applies to **Observable** `let observable = new Observable(this.sendSMS_obs);` `sendSMS_obs = (observer) => {setTimeout(()=>{this.nameFormControl.markAsTouched();/*http post request data=>*/observer.next("Booking successful"); observer.complete();});};` – novice in DotNet May 30 '22 at 12:33