0

I have a div that becomes visible / invisible based on a boolean variable. And i'm trying to add a timeout so my "actions" div could disapear after a few seconds.

This is how my code looks like now.

My 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. And aparently the div disapears when I interact with other component on the screen.

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...

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

  • 1
    Start by getting rid of the function + bind syntax, use an arrow function: `setTimeout(() => this.showMessageActions = false, 3000);` – Clashsoft Jun 21 '22 at 16:57

1 Answers1

0

Use the ChangeDetectorRef to trigger the detection manually:


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

    onTextMouseEnter(){
        this.showMessageActions = true;
        this.cd.detectChanges();
    }
    
    onTextMouseLeave(){
        window.setTimeout(function(){
            this.showMessageActions = false;
            this.cd.detectChanges();
        }.bind(this), 3000);
    }
Mahdi Rezazadeh
  • 511
  • 3
  • 10
  • I was looking into this and my component has a change detection strategy changeDetection : ChangeDetectionStrategy.OnPush when I remove this, the weird behavior stops .... Not sure if i can remove this permanently on this code – Raphael Amorminio Jun 21 '22 at 16:58
  • if **changeDetection: ChangeDetectionStrategy.OnPush** used, the above answer can solve your problem, otherwise, you can delete onPush line to make angular work regularly. – Mahdi Rezazadeh Jun 21 '22 at 17:00
  • I've tried both way. It works now ! thanks. – Raphael Amorminio Jun 21 '22 at 17:04
  • It is more about better performance you can read more on this [link](https://medium.com/angular-in-depth/boosting-performance-of-angular-applications-with-manual-change-detection-42cb396110fb) – Mahdi Rezazadeh Jun 21 '22 at 17:04