Search code examples
angularangular2-components

Listening for event in Angular 2


I feel like this should be really easy but I cannot get it to work. I am using screenfull which is included in a theme I'm using to make the browser fullscreen. I am trying to hook into the fullscreenchange event to perform actions when the either in full screen mode or not. The documentation clearly states the following example for doing this:

document.addEventListener(screenfull.raw.fullscreenchange, () => {
    console.log('Am I fullscreen? ' + (screenfull.isFullscreen ? 'Yes' : 'No'));
});

If I put this in my components ngOnInit method this outputs to the console as expected. But I know this is not the correct way to handle this situation in Angular so I have tried to implement it using the @HostListener decorator as follows:

@HostListener('screenfull.raw.fullscreenchange')
onFullScreenToggle() {
    console.log('Angular - Am I fullscreen? ' + (screenfull.isFullscreen ? 'Yes' : 'No'));
};

But no matter what I try it never picks the event up. I'm really hoping I've missed something really obvious and if someone could point it out I would be much appreciated.


Solution

  • Like Jesse said, first prefix with document: (or window: if needed), but notice when you used:

    document.addEventListener(screenfull.raw.fullscreenchange, () => { ... });
    

    you sent screenfull.raw.fullscreenchange as the first string argument to addEventListener, so I'm guessing screenfull.raw.fullscreenchange is a string representing an event name, so I'd imagine appending it as follows might work:

    @HostListener('document:' + screenfull.raw.fullscreenchange)
    onFullScreenToggle() {
        console.log('Angular - Am I fullscreen? ' + (screenfull.isFullscreen ? 'Yes' : 'No'));
    }