Reputation: 3376
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.
Upvotes: 4
Views: 10608
Reputation: 38807
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!
Upvotes: 12