我设置超时以在Angular 5中隐藏元素一段时间:
third
但是,这并不会更新视图。 this.showElement = true;
setTimeout(function () {
console.log('hide');
this.showElement = false;
}, 2000);
给了我一个输出,所以超时肯定有效。
我发现在Angularjs中你需要调用console.log
才能开始摘要,所以我猜测我只需要找到Angular 5等效的方法。
答案 0 :(得分:25)
我认为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);
或使用bind
:
this.showElement = true;
setTimeout(function() {
console.log('hide');
this.showElement = false;
}.bind(this), 2000);
将适当的上下文传递给setTimeout
回调函数。
答案 1 :(得分:3)
已更新:已更正答案。
正如其他人正确回答的那样,没有反映更改的原因是因为对this
引用的引用不正确。
请注意,使用function() { ... }
表示法时,对this
的引用是函数本身的上下文。所以
myFunction() {
this.showElement = true;
setTimeout(function() {
console.log(this.showElement); // Will result in undefined;
this.showElement = false; // Here, this, reference to context of the function wrapper
}, 2000);
}
将上述更改为ES6箭头表示法,将this
引用的上下文更改为父上下文。所以
myFunction() {
this.showElement = true;
setTimeout(() => {
console.log(this.showElement); // Will result in true;
this.showElement = false; // Here, value is updated
}, 2000);
}
详细了解lexical this
here。
答案 2 :(得分:3)
当你使用功能风格"这个"参考不起作用 像下面这样做,你的例子将正常工作
this.showElement = true;
setTimeout(() => {
console.log('hide');
this.showElement = false;
}, 2000);
答案 3 :(得分:2)
在构造函数中,添加一个更改检测器:
constructor(private cd: ChangeDetectorRef) {}
然后在您的 setTimeout 中:
setTimeout(() => {
console.log('hide');
this.showElement = false;
this.cd.detectChanges();
}, 2000);
答案 4 :(得分:0)
我在Angular 7应用中遇到了同样的问题。我必须更改按钮中标题和图标的来源:
<button class="btn btn--outline-red text-uppercase font-weight-normal product-action-btn mt-3"
(click)="addToCart()">
{{addToCartProps.title}}
<img style="width:15px; height:15px;" [src]="addToCartProps.src">
</button>
.......
addToCartProps = { title: 'Add to Cart', src: '' }
addToCart() {
this.addToCartProps.title = 'Adding';
this.addToCartProps.src = 'assets/images/preloader-white.svg';
setTimeout(() => {
this.addToCartProps.title = 'Added';
this.addToCartProps.src = 'assets/images/checked-icon-white.svg';
this.cd.markForCheck();
console.log('timeout 1 ', this.addToCartProps);
}, 1000);
setTimeout(() => {
this.addToCartProps.title = 'Add to cart';
this.addToCartProps.src = '';
this.cd.markForCheck();
console.log('timeout 2 ', this.addToCartProps);
}, 1500);
}
在超时功能中添加 this.cd.markForCheck()解决了我的问题。
@artemisian在Angular2, view not updating after variable changes in settimeout
中也对此进行了评论。答案 5 :(得分:0)
它正在更新值,但是问题是this
。您可以通过绑定或箭头功能设置此值。
setTimeout(function () {
console.log('hide');
this.showElement = false;
}.bind(this), 2000);
或者我们可以使用箭头函数,因为它的此值是包含函数的设置。
this.showElement = true;
setTimeout(() => {
console.log('hide');
this.showElement = false;
}, 2000);