Search code examples
angularmouseeventmouseenter

Prevent retriggering mouseenter on parent div when child hidden


I have a parent div where a user's mouse enters, then they click a child input to hide it (mousedown).

Is it possible to prevent triggering another mousenter on the parent div when the child is hidden?

For example, the sequence currently becomes:

onMouseEnter Blue Container
input mouseEnter
input hidden
onMouseEnter Blue Container 

I want to prevent the last "onMouseEnter Blue Container" from being triggered (i.e., parent mouseEnter should not trigger again).

Stackblitz is here: https://stackblitz.com/edit/angular-mouseenter-dquf3y

Below is my component:

<div [ngClass]="class" #target
    (mouseenter)="onMouseEnter($event)"
    (mouseleave)="onMouseLeave($event)">
    <input (mouseenter)="this.log('input mouseEnter')" 
           type="checkbox" (click)="doHide()" *ngIf="!hide"/>
</div>

Below is my TS:

onMouseEnter($event) {
    this.log('onMouseEnter Blue Container');
    this.isHovering = true;
  }

  onMouseLeave($event) {
    this.log('onMouseLeave');
    this.isHovering = false;
  }

  hide = false;
  doHide() {
    this.hide = !this.hide;
    if (this.hide === true) {
      this.log('input hidden')
    }
  }

Solution

  • Instead of removing the input element with:

    *ngIf="!hide"
    

    you can hide it with:

    [hidden]="hide"
    

    That appears to avoid the triggering of the mouseenter event on the parent.

    See this stackblitz for a demo.