How to properly attach an Event Listener to global 'window' in Angular 6+?
The "Angular" way of doing this is to use HostListener
https://angular.io/api/core/HostListener
Here is a stackblitz example for your review. Open console and review the log when using keys on the keyboard to trigger events.
https://stackblitz.com/edit/hostlistener-1
Related videos on Youtube
Alexander
Updated on June 04, 2022Comments
-
Alexander 4 months
Background
Our
Angular 6application contains aniframewith some 3rd party data. To enable a safe cross-domain communication the child iframe posts messages to parent Angular application using window.postMessage() API. In order to receive those messages parent window must attach an event listener likewindow.addEventListener("message", callback)to listen for MessageEventsQuestion
I need to listen for message events inside Angular component and it's not obvious for me how to properly access global
windowin Angular way. The only solution I imagine at the moment is:- Create an Angular Service called
MessageListenerServicewith the following method:
function listenForMessageEvent(callback) { this.renderer.listen('window', 'message', callback); }Note:
this.rendererhere is Renderer2 from Angular core.- Just use
MessageListenerService.listenForMessageEvent()in my custom component.
I feel like it's not the standard approach in Angular world. Could someone advise any best practise here?
Thanks a lot.
- Create an Angular Service called