Angular Passive Event Listeners
Asked Answered
M

2

9

It is quite stunning how the Internet is empty regarding this topic how to make an event listener passive in Angular.

I have a dropdown menu which, when scrolled on, throws an error in Chrome: [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive....

Google's motivation behind throwing this error and the problem itself is quite clear to me, and I know the solution. I need to make something like this work in my Angular code: document.addEventListener('wheel', (e) => { e.preventDefault() }, { passive: false }); But it seems the solution is harder to implement than I imagined. Angular does not have a means of setting an event listener to {passive: false}, and the vanilla JS I pasted above simply does not work.

Has anybody come across a similar problem/solution? Maybe there is a workaround? Any related information could be valuable, thanks.

Microprint answered 2/12, 2019 at 14:13 Comment(3)
Hi SharisM, could you try using https://angular.io/api/core/HostListener? There might be option for you to use there or optimized behaviors.Fiddlefaddle
Hello @mikegross, I'll give it a shot soon and we will see how it goes. Thanks.Microprint
@mikegross, tried it, but it did not work either. Maybe you could specify what exactly you had in mind? ThanksMicroprint
G
5

As specified in https://angular.io/guide/event-binding#binding-to-passive-events:

(window as any)['__zone_symbol__PASSIVE_EVENTS'] = ['scroll'];

can be added in the polyfills, which will make the event listeners for the scroll event passive

Gause answered 3/10, 2020 at 6:44 Comment(1)
The page you linked has been marked for archival. This is a better link: angular.io/guide/event-binding#binding-to-passive-events.Childers
D
0

document.addEventListener('wheel', (e) => { e.preventDefault() }, { passive: false }); should work. It works for me. Check that you're putting it in the right place, like an ngOnInit method.

Desmond answered 10/9 at 21:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.