角度setTimeOut()无法正常工作

时间:2019-02-13 12:01:49

标签: angular

我有div类警报。

    <div class="alert" *ngIf=alert>
      <h1>Copied</h1>
    </div>

我要显示此div 3秒钟。最初它是隐藏的,单击按钮后,我运行一个函数,然后将值更改为true,然后它变为可见。一切都在发生。但是,当我运行setTimeOut()函数时,三秒钟后,我想使div再次不可见,这是行不通的。

alert; //the value i am using to hide the div
//after clicking the function I am running the function
copying() {
    this.clipboard.copy(this.currentCode);
    this.alert = true;
    setTimeout(function() {
      this.alert = false;
      // the alert value is being change to false but the div is not hiding.
    }, 3000)
}

1 个答案:

答案 0 :(得分:2)

像这样更改代码-

setTimeout(() => {
  this.alert = false;
}, 3000);

这样做的原因是函数中this的值取决于函数的调用方式。

相关问题