omridevk / ng-keyboard-shortcuts

Dead Simple Keyboard Shortcuts Management for Angular

Home Page:https://ng-keyboard-shortcuts.vercel.app/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Lose focus when 'escape' key is pressed

zannkukai opened this issue · comments

Hello,

I try to implement a basic shortcut on "escape" key. When this key was pressed, I would like that the element with focus, lose this focus (any input elements, on any pages of my application). I tried to implements this behavior like this :

{
  key: ['escape'],
  label: 'Shortcuts list'
  description: 'Lose focus on the current field',
  allowIn: [AllowIn.Select, AllowIn.Input, AllowIn.Textarea],
  preventDefault: true,
  command: (output: ShortcutEventOutput) => output.event.target.blur()
}

This works but Angular isn't happy with this synthax when I run my tests with the following error message :
Property 'blur' does not exist on type 'EventTarget'.

I also tried with

@ViewChild('input', { static: false}) input: ElementRef;
...

{
  key: ['escape'],
  label: 'Shortcuts list'
  description: 'Lose focus on the current field',
  allowIn: [AllowIn.Select, AllowIn.Input, AllowIn.Textarea],
  preventDefault: true,
  target: this.input.nativeElement,
  command: (output: ShortcutEventOutput) => console.log(output)
}

But it also failed with the following error : Cannot read property 'nativeElement' of undefined

Do I miss something into the my configuration ?

commented

I used the native browser KeyboardEvent type, which does not seem to have blur on the event target, you will have to manually cast it using typescript.
something like:

(output.event.target as HTMLElement).blur();

Hopefully should fix the typescript error, I will try to see if I can use a different type for my event output type, for now this workaround should solve the Typescript errors and it is not fooling typescript, as you do get the native keyboard event which has the blur method on it.
Please let me know if the issue persist after this workaround.
And thank you for reporting the issue :) hopefully this will help.

It seems working better ;-) Jasmine tests still raises errors but it's another problem. See you soon about this error on Gitter ;-)