I am using the direct following and I do not detect the copy and paste with the keys inside the input, would someone know how? Thank you!
export class OnlyNumberDirective {
// Allow decimal numbers. The \, is only allowed once to occur
private regex: RegExp = new RegExp(/[0-9]+(\,[0-9]{0,1}){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = [ 'Backspace', 'Tab', 'End', 'Home', 'Delete', 'Del', 'Ctrl', 'ArrowLeft', 'ArrowRight', 'Left', 'Right' ];
constructor(private el: ElementRef) {
}
@HostListener('keydown', [ '$event' ])
onKeyDown(event: KeyboardEvent): string {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return null;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
let current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
return null;
} else {
return next;
}
}
}
Angular provides high level API for listening to key press combinations. Check out the following example.
ctrl-keys.directive.ts
Usage
Live demo
Just add this to any component. When the user performs the key combination Ctrl +s it will print 'Save Performed'
If you want Ctrl +v replace the 's' in 'document:keydown.control.s' with 'v'.
You simply can do who : for information this code manage all mac user who user CMD instead of ctrl
If you want to detect other kind of shortcut :
Online sample
--- UPDATE AFTER COMMENT ---
You may can do something like this
or if is not working, just :
Where
this.deviceService.getKeybordEvent();
is method who return type of event base on User Agent. massive list of user agent can be find hereInstead of monitoring the key events for copy and paste commands, I suggest handling the clipboard events (
copy
,cut
,paste
). In addition to taking care of the various shortcuts used on different platforms, it also detects the clipboard operations initiated with the context menu. Please note that thepaste
event can be cancelled withe.preventDefault()
. You can see the code at work in this stackblitz.