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?
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.