3

I need to capture keypress/keydown/keyup on any element. I did use a directive to handle it. So I defined a KeyPressedDirective :

 import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appKeyPressed]' }) export class KeyPressedDirective { constructor(elRef:ElementRef<HTMLElement>) { elRef.nativeElement.addEventListener('keypress',e=>console.log(e)); } } 

but by using the directive nothing happen and event did not capture.

 <p appKeyPressed>Capture keypoard events</p> 

How should I capture keyboard events?

Here is a StackBlits link: KeyPressDirective

1
  • 1
    keypress/keydown/keyup, These events will work on input element. Please try Commented Sep 19, 2021 at 6:00

4 Answers 4

2

To use events keypress/keydown/keyup on any element, the element should have the attribute tabindex. So changing the directive to this will solve the problem:

import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appKeyPressed]' }) export class KeyPressedDirective { constructor(elRef:ElementRef<HTMLElement>) { elRef.nativeElement.setAttribute('tabindex',0); // It can be checked that element has `tabindex` already elRef.nativeElement.addEventListener('keypress',e=>console.log(e)); } } 

Here is StackBlitz link: StackBlitz

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

Comments

1

U can use @HostListener(EVENT_NAME, [arguments you want to pass]) & BTW keypress means you are expecting Keyboard key press into an input, as I can see you are using a p paragraph I changed the code to use mouseover to demo @HostListener

import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appKeyPressed]' }) export class KeyPressedDirective { constructor() {} @HostListener('mouseover', ['$event']) customMouseOver($event) { console.log($event); } } 

Comments

1

You need to understand when you can capture the keyEvents. Key events can be keyUp or KeyDown only triggered in the input or text field when user uses the keyboard.

So, this directive can be useful on input or textarea.

<input appKeyPressed/> <textarea appKeyPressed> </textarea> 

How should I capture keyboard events?

Applying appKeyPressed on p tag won't give any results as there is no keyboard happening on it instead you can use mouse events like mouse-move-in or mouse-move-out. For that you can add HostListener too, but you can inbuilt methods:

<div (mouseover)="doSomething(whencursoroverParagraph)" (mouseout)="doSomething(whencursoisoutFromParagraph)"> </div> 

Comments

0

<input appKeyPressed/>

This will work with keypress event, Please try

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.