本文介绍了Angular 5视图超时后不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我设置超时以在Angular 5中隐藏一段元素:
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);
但是,这不会更新视图。 console.log
给了我一个输出,所以超时肯定有效。
However, this doesn't update the view. The console.log
gives me an output, so the timeout definitely works.
我在Angularjs找到了你需要调用 $ apply
才能开始摘要,所以我猜我只需要找到Angular 5等效的方法。
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.
推荐答案
我认为 setTimeout
回调会将范围丢失到变量showElement。
I think the setTimeout
callback lose a scope to a variable "showElement".
this.showElement = true; // this - is in component object context
setTimeout(function () {
console.log('hide');
this.showElement = false; // here... this has different context
}, 2000);
你应该使用箭头功能:
this.showElement = true;
setTimeout(() => {
console.log('hide');
this.showElement = false;
}, 2000);
或使用 bind
:
this.showElement = true;
setTimeout(function() {
console.log('hide');
this.showElement = false;
}.bind(this), 2000);
将正确的上下文传递给 setTimeout
回调功能。
to pass proper context to the setTimeout
callback function.
这篇关于Angular 5视图超时后不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!