1

I have a page in ionic 2 and I want to catch key pressed when the user is in the page. This is the code I used to do this (.ts)

@Component({
  selector: 'page-play',
  templateUrl: 'play.html'
})

export class PlayPage {
  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvents(event: KeyboardEvent) {
    console.log("keypressed!");
  }

  constructor() {
    // doing a lot of things
  }
}

Unfortunately, the handleKeyboardEvents gets fired once the first time I enter in the page, twice if, after that, i navigate some other pages in the app and then go back to the page, three times if I exit and enter again and so on...

What can cause this?

EDIT: In the end, in my case, it turned out that the problem was that I was 'stacking' multiple times that page. The flow of the application was something like

Homepage -> Play Page -> EndPlay Page (and if you choose to play again) -> Play Page

The Play Page was presented again with a second 'push' (this.navCtrl.push) so to appear multiple times in the stack and, every one of it, had is own HostListener, firing events.

I've not yet come out with a clean solution for I don't really know how to manage correctly the stack, so I won't propose a real code solution for this. In some way, the solution is avoiding to push multiple times a page.

Sasha Grievus
  • 2,566
  • 5
  • 31
  • 58
  • 1
    probably it is getting binded more than once. Here is a post where hostlistner is removed: https://stackoverflow.com/a/44425208/1791913. You can probably remove your host listener in ngOnDestroy .. just an idea I have not worked on such thing. Also check this discussion: https://github.com/angular/angular/issues/16366 – FAISAL Aug 04 '17 at 14:15

0 Answers0