gkeenley
gkeenley

Reputation: 7348

Angular: why does 'keydown' event listener fire multiple times?

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?

Upvotes: 1

Views: 2595

Answers (1)

bryan60
bryan60

Reputation: 29315

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.

Upvotes: 6

Related Questions