简体   繁体   中英

Listen to Custom DOM Events in Angular

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?

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.

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.

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

Parent:

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

Child:

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

Here is an example in action.

Hopefully that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM