Home > Net >  Angular HostListener with custom event : possible?
Angular HostListener with custom event : possible?

Time:11-25

I wonder if I can catch up with custom event (EventEmiter). I have a child component that emit event with @Output('myCustomEvent).

Can I catch it in my parent component with @HostListener('myCustomEvent') ?

I try to di this so I get rid of the (myCustomEvent)="myMethod" in my html, which I think my be better (cleaner html code).

Can I do that ?

Thank you ahead for your help :)

CodePudding user response:

You can listen to custom events with HostListener, however you need to listen to the element which dispatches the event.

The easiest way to achieve this would be to use the window to dispatch the event:

// some component class:
produceEvent() {
  window.dispatchEvent(new CustomEvent("yourEventType", {detail: yourData}))
}

Then in the component which needs to listen for these events you would simply wire up the HostListener to listen for your event:

// some other component class:
@Component({template: ''})
export class SomeOtherComponent {
  @HostListener("window:yourEventType", ["$event"])
  eventHandlerFunction(event: any) { 
     // process event here:
  }
}

I don't know if I would recommend this approach, as you are circumventing the normal Angular structure of utilizing Services. See: https://angular.io/tutorial/toh-pt4

CodePudding user response:

I would say no.

"Host" here is where the directive attached to. Yes, it's meant to use with directive not component.
And here is the official docs from Angular:

The child's EventEmitter property is an output property

I mean, they have a name for it - output property => @output event. They go hand in hand together.

  • Related