setTimeOut for elementRef



我正在使用angular2。我有一个Div:

<div class="saved" #saved>
    <p>Saved</p>
    <i class="fa fa-check" aria-hidden="true"></i>
</div>

我在TS中访问它:

@ViewChild("saved") public saved: ElementRef;

接下来我显示块:

this.saved.nativeElement.style.display = 'block';

,然后我想在几秒钟后隐藏它,但是我的代码的这一部分不正确:

setTimeout(this.closeSavedWindow, 3000);

其中

closeSavedWindow() {
    this.saved.nativeElement.style.display = 'none';
  } 

错误是

typeerror:this.saved是未定义的

尝试setTimeout(this.closeSavedWindow.bind(this), 3000);

您面临的问题是由于上下文的变化所致。在collesavedwindow()函数内部,这是指 window对象,并且不包含任何名为"保存的属性"。因此错误。

调用函数的上下文值可以轻松修复。

setTimeout(this.closeSavedWindow.bind(this), 3000);

最新更新