我在 Angular 5 中设置了一个超时,在一段时间后隐藏元素:
this.showElement = true;
setTimeout(function () {
console.log('hide');
this.showElement = false;
}, 2000);
但是,这不会更新视图。这console.log
给我一个输出,所以超时肯定有效。
我发现在 Angularjs 中你需要调用$apply
为了开始摘要,所以我猜我只需要找到 Angular 5 的等效方法即可。
我觉得setTimeout
回调失去了“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);
Or use bind
:
this.showElement = true;
setTimeout(function() {
console.log('hide');
this.showElement = false;
}.bind(this), 2000);
将适当的上下文传递给setTimeout
回调函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)