问题
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.
来源:https://stackoverflow.com/questions/45508829/why-using-hostlistener-keypress-event-fires-a-number-of-time-equal-of-the-tim