Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 View Not Updating After Timeout

Tags:

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.

like image 640
Peter Avatar asked Feb 21 '18 08:02

Peter


1 Answers

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.

like image 192
Krzysztof Raciniewski Avatar answered Oct 05 '22 03:10

Krzysztof Raciniewski