In my Angular app, I have implemented a context menu, and want to trigger an event when a particular key (up or down) is pressed. I have tried placing (keydown)="onKeydown($event) in my outer div, but it doesn't detect any key presses. It does detect a mouseover event if I place (mouseover)="onKey()" in the same div. Does anyone know how to approach this?
Add a comment
|
1 Answer
you can try like this
import { Inject, OnDestroy, OnInit } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { fromEvent } from 'rxjs/internal/observable/fromEvent';
import { Subscription } from 'rxjs/internal/Subscription';
export class Component implements OnInit, OnDestroy {
subscription: Subscription;
// and in your constructor import documnet
constructor(@Inject(DOCUMENT) private document: Document) {}
// and in some lificicle hook or in constructor
ngOnInit() {
this.subscription = fromEvent(this.document, 'keydown').subscribe(event => {
// do some thing
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
I hope this helps you.
4 Comments
RNdev
thanks for your quick reply. This is successfully triggering a response, but I notice if I press a key it triggers three consecutive identical events. Do you know why this would be?
Ashot Aleqsanyan
I think I know why. You need to unsubscribe from subscription when your component is destroys. let me update my answer
RNdev
Thanks, I accepted your answer, I found a simpler approach that does the same thing, just adding
window.addEventListener() in the constructor of the context menu. The problem I'm having, which also happened when I used your code, is that when I move the mouse off the context menu, key presses no longer trigger the event, even if I then move the mouse back over the menu. Any ideas on that?Ashot Aleqsanyan
@RNdev Please can you create a simple example so that I can help you?