30 seconds of angular
Star
✨✨ New to Angular? Check out interactive Angular Codelab ✨✨

Global event listeners

It is possible to add global event listeners in your Components/Directives with HostListener. Angular will take care of unsubscribing once your directive is destroyed.

@Directive({
      selector: '[rightClicker]'
    })
    export class ShortcutsDirective {
      @HostListener('window:keydown.ArrowRight')
      doImportantThings() {
        console.log('You pressed right');
      }
    }
    

Bonus

You can have multiple bindings:

@HostListener('window:keydown.ArrowRight')
    @HostListener('window:keydown.PageDown')
    next() {
      console.log('Next')
    }
    

You can also pass params:

@HostListener('window:keydown.ArrowRight', '$event.target')
    next(target) {
      console.log('Pressed right on this element: ' + target)
    }