I'm setting a timeout to hide an element after a while in Angular 5:
this.showElement = true; setTimeout(function () { console.log('hide'); this.showElement = false; }, 2000);
However, this doesn't update the view. The console.log
gives me an output, so the timeout definitely works.
I have found that in Angularjs you needed to call $apply
in order to start a digest, so I'm guessing I just need to find the Angular 5 equivalent way of doing that.
I think the setTimeout
callback lose a scope to the "showElement" variable.
this.showElement = true; // this - is in component object context setTimeout(function () { console.log('hide'); this.showElement = false; // here... this has different context }, 2000);
You should use arrow function:
this.showElement = true; setTimeout(() => { console.log('hide'); this.showElement = false; }, 2000);
Or use bind
:
this.showElement = true; setTimeout(function() { console.log('hide'); this.showElement = false; }.bind(this), 2000);
to pass proper context to the setTimeout
callback function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With