Angular 将所有鼠标事件从父组件传递到子组件-角度6

Angular 将所有鼠标事件从父组件传递到子组件-角度6,angular,typescript,Angular,Typescript,我有一个父组件,我想将其中发生的所有鼠标事件传递给一个子组件,该子组件包含3个不同的组件,这些组件取决于要传递的数据。 我的目标不是在父组件内使用事件侦听器,而是在子组件内使用事件侦听器,并处理子组件内的所有逻辑 <div class="some-class"> // Pass all mouse events from here <app-child-component> // To here <app-child-of-child-component

我有一个父组件,我想将其中发生的所有鼠标事件传递给一个子组件,该子组件包含3个不同的组件,这些组件取决于要传递的数据。
我的目标不是在父组件内使用事件侦听器,而是在子组件内使用事件侦听器,并处理子组件内的所有逻辑

<div class="some-class"> // Pass all mouse events from here 

 <app-child-component> // To here
   <app-child-of-child-component-1></app-child-of-child-component-1>
   <app-child-of-child-component-2></app-child-of-child-component-2>
   <app-child-of-child-component-3></app-child-of-child-component-3>
 </app-child-component>

</div>
起初,我想用
@HostListners
而不是子组件创建一个指令,并将其绑定到父元素,但由于子组件中有组件,所以我没有选择它

如有任何疑问,我们将不胜感激

示例:

<div class="some-class"> // Pass all mouse events from here 

 <app-child-component> // To here
   <app-child-of-child-component-1></app-child-of-child-component-1>
   <app-child-of-child-component-2></app-child-of-child-component-2>
   <app-child-of-child-component-3></app-child-of-child-component-3>
 </app-child-component>

</div>
//从此处传递所有鼠标事件
//到这里

您可以创建一个指令来侦听所有鼠标事件

@Directive({
  selector: "[appMouseListener]"
})
export class MouseListenerDirective {
  constructor() {}

  private enterSub = new Subject<MouseEvent>();

  public enter = this.enterSub.asObservable();

  @HostListener("mouseenter", ["$event"]) onMouseEnter(event: MouseEvent) {
    this.enterSub.next(event);
  }
}
在父组件上添加此指令

<parent-component appMouseListener>
  <child-component></child-component>
</parent-component>

您可以创建一个指令来侦听所有鼠标事件

@Directive({
  selector: "[appMouseListener]"
})
export class MouseListenerDirective {
  constructor() {}

  private enterSub = new Subject<MouseEvent>();

  public enter = this.enterSub.asObservable();

  @HostListener("mouseenter", ["$event"]) onMouseEnter(event: MouseEvent) {
    this.enterSub.next(event);
  }
}
在父组件上添加此指令

<parent-component appMouseListener>
  <child-component></child-component>
</parent-component>

将事件侦听器添加到父元素。当一个子元素触发该事件时,侦听器也将触发。您只需要区分谁是触发事件的孩子,并根据单独的逻辑处理它为什么不能使用HostListner?我相信,它可以在任何级别被捕获。您可以向父元素添加事件侦听器。当一个子元素触发该事件时,侦听器也将触发。您只需要区分谁是触发事件的孩子,并根据单独的逻辑处理它为什么不能使用HostListner?我相信,它可以在任何级别被捕获。