Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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.

like image 611
Michail Michailidis Avatar asked Dec 24 '22 23:12

Michail Michailidis


1 Answers

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

like image 116
slaesh Avatar answered Dec 28 '22 10:12

slaesh