0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
I think I know why. You need to unsubscribe from subscription when your component is destroys. let me update my answer
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?
@RNdev Please can you create a simple example so that I can help you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.