@HostListener docs do not mention option to listen to global events
See original GitHub issueI’m stil relatively new to Angular, so it’s probable that someone with more knowledge could guess this. But it seems to me that this options should be mentioned; it’s anything but self-evident that a decorator that connects to DOM events targeted at the host element can also subscribe to window events, let alone how that is done.
For example, I had found @HostListener somewhere on the internet, and used it as I had found it, which was with “window:” prepended to the event name. This appeared to work for me, until I noticed that my keyboard handler would react even when my component wasn’t focused. It took me a while to figure out that the prepended “window:” was actual non-standard usage.
@HostListener('window:keydown', ['$event'])
handleKeyDown(event: KeyboardEvent) {
console.log('handleKeyDown:', event);
//...
Issue Analytics
- State:
- Created 4 years ago
- Comments:8 (6 by maintainers)
Top Results From Across the Web
HostListener - Angular
Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs. See more... Option,...
Read more >Four ways of listening to DOM events in Angular (Part 2
Let's see an example of using @HostListener to listen to a DOM event in a directive. I will use and expand my previous...
Read more >angular - Angular2, HostListener, how can I target an element ...
@HostListener() only supports window , document , and body as global event targets, otherwise it only supports the components host element.
Read more >Simple Angular context help component or how global event ...
We utilized two HostListeners that are listening to global events. Each time user clicks on document or hits Escape button Angular will trigger...
Read more >Nobody has to use HostListener - angular
The @hostListener decorator is handy if we just want to listen to single events and don't rely on any kind of composition. Everything...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

@JPGygax68, please check the below example is good enough to grab an idea about HostListner usage. If something more is required, please let me know.
@kapunahelewong PR created with an example which mentioning how we could handle a global event.
https://github.com/angular/angular/pull/34228