最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Using @HostListener in Angular, on doing ctrl+v, Paste event not triggered when keydown event is also there AND on

programmeradmin3浏览0评论

On input type="text", I am using two directives - keydown and paste.

My requirement is:

  • I need to validate user input string character by character which will be done in keydown event,
  • I need to allow user to paste value in text box using either ctrl+v or right click and paste

Below is my code block:

  @HostListener("paste", ["$event"])
  onPaste(event: ClipboardEvent) {
    debugger;
    alert('onPaste');
    const clipboardData = event.clipboardData || window['clipboardData'];
    const pastedText = clipboardData.getData('text');
  }

  @HostListener("keydown", ["$event"])
  onKeyDown(event: KeyboardEvent) {
    debugger;
    alert('onKeyDown');
  }

When I do right click and paste, paste event is triggered and keydown is not triggered so not a problem here.

My problem is:

  • When both events - keydown and paste are in directives, on pasting using ctrl+v, only keydown event is triggered and event.key = "Control" and event.keycode = 17. Paste event is not triggered.
  • When only event - paste is in directive, on pasting using ctrl+v, Paste event is triggered.

My need is:

On doing ctrl+v, either Paste event need to trigger when keydown event is also there OR on keydown event, ctrl+v should be detected.

What I have tried to detect CTRL+V in keydown?

Added line event.ctrlKey && (event.key === 'v' || event.keyCode === 86) as shown below but event.ctrlKey = "Control" and keycode is not 86. So, ctrl+v is not detected.

 onKeyDown(event: KeyboardEvent) {
   debugger;
   alert('onKeyDown');    
   if (event.ctrlKey && (event.key === 'v' || event.keyCode === 86)) {
     alert('paste triggered from keydown');
     return;
   }
 }

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论