【问题标题】:Pass all mouse events from parent to child component - Angular 6将所有鼠标事件从父组件传递到子组件 - Angular 6
【发布时间】:2019-10-04 15:45:32
【问题描述】:

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

起初我想用@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>

【问题讨论】:

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

标签: angular typescript


【解决方案1】:

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

@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);
  }
}

如果您需要,您可以过滤发出的事件以仅发出父事件。这是事件目标将是父组件元素。

export class MouseListenerDirective {

  constructor(private el: ElementRef){}

  public enter = this.enterSub.asObservable().pipe(filter(x => x.target === this.el.nativeElement));

...

在父组件上添加该指令

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

通过注入指令访问子组件上的事件

@Component({ // configs}
export class ChildComponent {

  constructor(mouseListener: MouseListenerDirective){
    mouseListener.enter.subscribe(x => console.log(x)); // don't forget to manage subscriptions
  }
}


【讨论】:

    猜你喜欢
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2017-06-25
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多