Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  119] [ 2]  / answers: 1 / hits: 63084  / 6 Years ago, wed, february 21, 2018, 12:00:00

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.


More From » angular

 Answers
17

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.


[#55097] Friday, February 16, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiyam

Total Points: 448
Total Questions: 96
Total Answers: 92

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;