Search code examples
angularangular-directive

Angular 2+ How can I trigger a toggle directive by a mouseleave event in a sibling component


When the user's mouse enters the yellow square (found in the yellow component) the appToggle directive is triggered (making isActive = true) changing the squares background to grey, this works.

However I would like to be able to trigger the directive via the sibling component (the blue square found in the blue component) making (isActive = false) when the user's mouseleave's the blue square.

Please see stackblitz code example showing the problem.

toggle.directive.ts

  @HostListener('mouseleave', ['$event'])
  onMouseLeave(event) {
    if (event.target.classList.contains('blue')) {
      this.isActive = false;
    }
  }

The problem is that...

event.target.classList.contains('blue')

is being completely ignored, I get no errors, but nothing is actually happening.

I have searched everywhere to find a similar example which might solve this problem but have not been able to.

Any help would be greatly appreciated, many thanks in advance folks!


Solution

  • I found a working solution, mouseout which makes use of mouse event bubbling. Code changed to the following...

    @HostListener('document:mouseout', ['$event'])
      onMouseOut(event) {
        if (event.target.classList.contains('blue')) {
          this.isActive = false;
        }
      }
    

    For the sake of brevity and should anyone else be interested I also updated stackblitz with the working solution