Search code examples
angularonclickkeypresskeyup

detect key that has been press on mouse click in Angular 2


I have a angular 2 component with a div bind to a click event:

<div #myDiv class="myClass"
    (click)="addAnnotation($event)">
</div>

on click I would like to run the code addAnnotation only if the key 'a' is pressed:

addAnnotation(event) {
    if (the key 'a' is pressed) {
        code to run
    }
}

Do you know how to accomplish this?

UPDATE

I know there are keyboard events available on inputs but here I am asking if it is possible to detect which key is pressed when a mouse click occurs. The reason is that I would like to attach a dynamically created element in the point clicked only if the key 'a' is pressed.


Solution

  • Here is an example stackblitz

    1/ you have to make your component focusable

      @HostBinding('attr.tabIndex') tabIndex = -1;
    

    and for prevent outline to ruin your ui you can add the css

     :host { outline: none !important }
    

    2/ then you can listen to keypress event to stock the current active key, and keyup to flush it.

    3/ Then on click, you check the active key to see if the 'a' is pressed and run your code.