在Angular中收听自定义DOM事件

在Angular中收听自定义DOM事件

本文介绍了在Angular中收听自定义DOM事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Angular库,该库具有一个组件,该组件使用CustomEvents调度某些内容,如下所示:

I use an Angular library, which has a component, which uses CustomEvents to dispatch something, like this:

const domEvent = new CustomEvent('unselect', {
   bubbles: true
});
 this.elementRef.nativeElement.dispatchEvent(domEvent);

如何在父组件中收听此事件?

How can I listen to this Event in the parent component?

我知道不建议这样做,我通常应该使用 EventEmitters .但是我无权覆盖子组件,也没有定义 @Output 事件.所以这是我唯一可以使用的东西.

I know it is discouraged and I should normally use EventEmitters. But I have no access to overwrite the child component and there is no @Output Event defined. So this is the only thing I could use.

推荐答案

您可以使用 HostListener 收听此自定义事件.以下示例从子组件触发自定义事件,而父组件监听该事件.您甚至可以使用args(第二个参数),例如 ['$ event.target'] 来确定触发事件的元素.

You can use HostListener to listen for this custom event. The following example triggers the custom event from a child component with the parent component listening for the event. You can even use args (second argument) such as ['$event.target'] to determine what element triggered the event.

这使用了 ngAfterViewInit()生命周期钩子,但这只是为了演示,只是为了确保元素ref准备就绪.

This uses ngAfterViewInit() lifecycle hook, but it's just for demonstration and just to ensure the element ref is ready.

父母:

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  @HostListener('unselect', ['$event.target'])
  onUnSelect(el) {
    console.log(el); // element that triggered event, in this case HTMLUnknownElement
    console.log('unselect triggered');
  }
}

孩子:

import { Component, Input, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  @Input() name: string;

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    const domEvent = new CustomEvent('unselect', { bubbles: true });
    this.el.nativeElement.dispatchEvent(domEvent);
  }
}

这是一个正在使用的示例.

希望有帮助!

这篇关于在Angular中收听自定义DOM事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:34