Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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!


Post a Comment for "Listen To Custom DOM Events In Angular"