Michail Michailidis
Michail Michailidis

Reputation: 12171

How to subscribe to global events (e.g. keypress) in a component

Currently I have a suggestion menu component and, when the corresponding event happens, I increment the corresponding variable (pressedUp, pressedDown, pressedEnter) in the parent component using the suggestion-menu in its template.

<suggestion-menu             
  [pressedUp]="pressedUp" 
  [pressedDown]="pressedDown" 
  [pressedEnter]="pressedEnter" 
  [query]="someQuery" 
  (onSuggestionClicked)="doSomething($event)">
</suggestion-menu>

Then in the suggestion menu component I detect the change with something like that:

ngOnChanges(inputChanges) {
    if (inputChanges.pressedUp) {
        //do Something
    }

    if (inputChanges.pressDown) {
        //do Something
    }

    if (inputChanges.pressedEnter) {
        //do Something
    }
}

Can this be done in a better, less hacky and more event-oriented way? I would like all the key events that happen in the window to be listened for by the suggestion menu component. Then, if it is something important to it (e.g up, down or enter pressed), it will need to handle it on its own.

Upvotes: 5

Views: 3145

Answers (1)

slaesh
slaesh

Reputation: 16917

You should use the HostListener decorator for this: https://angular.io/docs/ts/latest/api/core/index/HostListener-interface.html

import {Component, NgModule, HostListener} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }

  @HostListener('window:keyup', ['$event'])
  onKeyup(event: any) {
    console.log('keyup..', event);
  }

  @HostListener('window:keyup.enter', ['$event', 'undefined'])
  @HostListener('window:click', ['undefined', '$event'])
  onEnterOrClick(enterEvent, mouseEvent) {
    if (enterEvent) {
      console.log('enter..');
    }
    if (mouseEvent) {
      console.log('click..');
    }
  }

  @HostListener('window:keyup.arrowUp')
  onarrowUp() {
    console.log('arrowUp..');
  }

  @HostListener('window:keyup.arrowDown')
  onarrowDown() {
    console.log('arrowDown..');
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

https://plnkr.co/edit/gx49kaDYFvBVlHo18bru?p=preview

Upvotes: 11

Related Questions