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.
when you use function style "this" reference is not working do it like following and your example will work correctly
Updated: Corrected answer.
As the others has correctly answered, the reason why the changes are not being reflected is because of the incorrect reference to the
this
reference.Note that when using the
function() { ... }
notation, the reference tothis
is the context of the function itself. SoChanging the above to ES6 arrow notation, changes the context of the
this
reference to the parent context. SoRead more about the
lexical this
here.I think setTimeout callback lose scope to a variable "showElement".
You should use arrow function:
Or use bind:
to pass context to setTimeout callback function.
I faced the same problem in my Angular 7 app. I had to change the source of title and icon in button:
.......
Adding this.cd.markForCheck() in timeout function solved the problem in my case.
Earlier this was also commented by @artemisian in Angular2, view not updating after variable changes in settimeout