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;
}
}