简体   繁体   English

几秒钟后隐藏一个 DIV

[英]Hidding a DIV after a few seconds

I have a div that becomes visible / invisible based on a boolean variable.我有一个基于 boolean 变量变得可见/不可见的 div。 And i'm trying to add a timeout so my "actions" div could disapear after a few seconds.而且我正在尝试添加超时,以便我的“动作”div 可以在几秒钟后消失。

This is how my code looks like now.这就是我的代码现在的样子。

My html:我的html:

<div class="text" (mouseenter)="onTextMouseEnter()" (mouseleave)="onTextMouseLeave()">
   <div class="text">
       ...Some Text... 
   <div>
    <div class="actions" *ngIf="showMessageActions">
        <mat-icon>settings</mat-icon>
    </div>
</div>



And my component methods还有我的组件方法

    onTextMouseEnter(){
        this.showMessageActions=true
    }
    
    onTextMouseLeave(){
        window.setTimeout(function(){
            this.showMessageActions=false
        }.bind(this), 3000);
    }


it's working without the window timeout.它在没有 window 超时的情况下工作。 And aparently the div disapears when I interact with other component on the screen.当我与屏幕上的其他组件交互时,显然 div 消失了。

not sure why angular doesn´t update the component after the variable update on the mouse leave event when I tried to use the timer...不确定为什么 angular 在我尝试使用计时器时鼠标离开事件的变量更新后不更新组件......

I looked for it on the forum and found this similar post but the accepted solution doent's solved the problem.我在论坛上查找并找到了这篇类似的帖子,但公认的解决方案并没有解决问题。 Any help would be apreciated任何帮助将不胜感激

Use the ChangeDetectorRef to trigger the detection manually:使用 ChangeDetectorRef 手动触发检测:


  constructor(
    .
    .
    private cd: ChangeDetectorRef,
  ) {
  }

    onTextMouseEnter(){
        this.showMessageActions = true;
        this.cd.detectChanges();
    }
    
    onTextMouseLeave(){
        window.setTimeout(function(){
            this.showMessageActions = false;
            this.cd.detectChanges();
        }.bind(this), 3000);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM