How to listen to children elements events in a directive?

maximedupre picture maximedupre · Nov 17, 2016 · Viewed 9.1k times · Source

Since there is no template, what's the best way to listen to child elements event in a directive? Is it possible with HostListener? If not, is there any other way?

There's also this similar question: How to listen for child event from parent directive in Angular2, but the suggested approach does not solve my problem, as my directive and child element aren't in the same template (directive is on host).

Cheers!

Edit #1

This is how I'm currently doing it (there has to be a better way):

First injecting ElementRef into my directive:

constructor(private elView: ElementRef) {}

Then binding with jQuery (or plain JS):

$(this.elView.nativeElement)
.on('drag', '#childId', this.slide.bind(this))

Answer

Günter Zöchbauer picture Günter Zöchbauer · Nov 21, 2016

If the event you want to listen to is a native DOM event that bubbles, then you can just use @HostListener()

@HostListener('click', ['$event'])
handleClick(event) {
  // handle event
}

If they are outputs of child components, you can query them and subscribe to their outputs

@ContentChildren(ChildComponent) children:QueryList<ChildComponent>;

ngAfterContentInit() {
  this.children.toArray().forEach((item) => {
    item.someOutput.subscribe(...);
  });
}

or you can use the approach used in the answer you linked to in your question.