30秒学会 Angular 片段 · 2020年3月16日

30秒学会 Angular 片段 – 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)
}

file:app.component.ts

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h2>Try using your keyboard.</h2>
    <h1>Last pressed: {{lastPressed}} </h1>
  `
})
export class AppComponent {
  lastPressed = 'nothing';
  @HostListener('window:keydown', ['$event.key'])
  next(key: string) {
    this.lastPressed = key;
  }
}

翻译自:https://www.30secondsofcode.org/angular/s/global-event-listeners