1

I have the following code in an event listener declared in the constructor of a component in my Angular app:

window.addEventListener('keydown, event => { console.log('key pressed'); });

This fires whenever I press any key while the component exists. The problem is that it fires 6 times instead of once.

What I Want To Know:

1) Why does it fire more than once?

2) How can I make it fire only once?

gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • https://stackoverflow.com/questions/6087959/prevent-javascript-keydown-event-from-being-handled-multiple-times-while-held-do – MikeOne Dec 09 '19 at 15:48
  • It's really get reproduced ) You can put this code to `OnInit` for now, i'll try to find what is problem with constructor – Yuriy Yakovenko Dec 09 '19 at 15:51
  • Did you remove the listener from an `OnDestroy?` You probably have multiple listeners registered. – Ruan Mendes Dec 09 '19 at 15:53

1 Answers1

6

can't say for sure but the problem looks like that you're manually registering an event listener everytime this component instantiates and never clearing it, and you're creating a memory leak where the listeners and components never get destroyed properly. this is part of why you don't want to do this sort of thing manually and should let angular handle it for you:

@HostListener('window:keydown', [])
onWindowKeyDown() {
  console.log('keydown')
}

now angular will handle registering / unregistering your listeners.

bryan60
  • 28,215
  • 4
  • 48
  • 65
  • Thanks, I'll try this. In the mean time, could you explain a bit more what using HostListener does for you in terms of registering/unregistering listeners? – gkeenley Dec 09 '19 at 15:55
  • 1
    HostListener does what the name suggests, it registers a listener on a given target for a given event and calls the function it's decorating. It also automatically handles removing that listener when a component gets destroyed. – bryan60 Dec 09 '19 at 15:56
  • 1
    Seems @bryan60 is right, here is a working example: https://stackblitz.com/edit/angular-49ogbe – Yuriy Yakovenko Dec 09 '19 at 15:57
  • This works, thanks! Thanks to Yuriy too for the stackblitz. – gkeenley Dec 09 '19 at 16:38