Can Angular use capture rather than bubbling to catch events?
Asked Answered
B

3

20

I somehow need capture method to catch triggered events, but ($event) in template is triggered in bubbling method by default. Is there somewhere to change it?

Banger answered 6/4, 2017 at 10:54 Comment(0)
S
18

Currently this can only be done adding event handlers imperatively.

There are plans though to support that in the future

See

Sideward answered 6/4, 2017 at 11:19 Comment(6)
Thank you so much, I have found a workaround with inspirations of your links.Banger
Glad to hear :)Tank
@Liranius, could you share your solution?Representational
Does Angular (5+) support "capture" on click event now?Impress
I don't think so. I didn't work with Angular the last 6 months and don't follow that closely what's happening but I couldn't find anything in github.com/angular/angular/blob/master/CHANGELOG.md and above issues are still open.Tank
the angular still has no support for capturing phase :(Spartacus
S
8

One workaround is to use the naive approach and add an event listener in your component's constructor.

Then add 'true' as the 3rd parameter to achieve event capturing.

constructor() {

    document.addEventListener('click', (event) => {

      console.log(event);

    }, true);

}

Tip: use the fat arrow function to reference the correct 'this'

Sandell answered 28/6, 2018 at 15:33 Comment(0)
L
3

You can create an observable with RxJS

this.documentScroll$ = fromEvent(document, 'scroll', { capture: true });

And subscribe to it to capture the event.

this.documentScroll$.subscribe((event) => {
  console.log(event);
});
Leatherneck answered 18/1, 2023 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.