Angular 2+ 如何通过兄弟组件中的 mouseleave 事件触发切换指令

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

当用户的鼠标进入黄色方块(在黄色组件中找到)时,将触发 appToggle 指令(使 isActive = true)将方块背景更改为灰色,这有效 .

但是我希望能够通过兄弟组件(蓝色组件中的蓝色方块)触发指令,当用户的鼠标离开蓝色方块时生成 (isActive = false)。

请参阅stackblitz code example showing the problem

toggle.directive.ts

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

问题是……

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

被完全忽略了,我没有收到任何错误,但实际上什么也没有发生。

我到处搜索,想找到一个类似的例子,可能会解决这个问题,但一直没能解决。

非常感谢任何帮助,非常感谢大家!

您应用的指令对蓝色方块一无所知。

来自文档:

The @HostListener decorator lets you subscribe to events of the DOM element that hosts an attribute directive

https://angular.io/guide/attribute-directives#directives-overview

所以 event.target 在你的例子中包含对黄色方块的引用

您可以通过多个路径达到预期效果,但最合理的可能是创建两个指令:

appToggle - 应在鼠标输入时切换其状态

appToggleSwitch - 应该接受对组件的引用(https://angular.io/guide/template-syntax#ref-vars)它需要在某些事件中更改:

appToggleSwitch 指令:

  @Input('appToggleSwitch') componentToToggle: any;

  @HostListener('mouseleave', ['$event'])
  onMouseLeave(event) {
    this.componentToToggle.classList.add('grey');
  }

应用组件:

<div class="yellow" appToggle #yellow></div>
<div class="blue" [appToggleSwitch]=yellow></div>

我找到了一个有效的解决方案,mouseout 它利用了鼠标事件冒泡。代码更改为以下...

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

为了简洁起见,如果其他人有兴趣,我也更新了 stackblitz with the working solution