Angular 5 View Not Updating After Timeout
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.
In your constructor, add a change detector:
constructor(private cd: ChangeDetectorRef) {}
And then in your setTimeout:
setTimeout(() => {
console.log('hide');
this.showElement = false;
this.cd.detectChanges();
}, 2000);