在浏览器的输入中检测Ctrl + C和Ctrl + V.

Mar*_*cía 5 directive keyboard-events onkeydown angular

我正在使用直接跟随,我没有检测到复制和粘贴输入内的键,有人会知道如何?谢谢!

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Yan*_*git 8

您只需执行以下操作即可:信息仅供参考,此代码管理所有使用CMD而不是ctrl的mac用户

@HostListener('window:keydown',['$event'])
onKeyPress($event: KeyboardEvent) {
    if(($event.ctrlKey || $event.metaKey) && $event.keyCode == 67)
        console.log('CTRL + C');
    if(($event.ctrlKey || $event.metaKey) && $event.keyCode == 86)
        console.log('CTRL +  V');
}
Run Code Online (Sandbox Code Playgroud)

如果要检测其他类型的快捷方式:

  • event.ctrlKey
  • event.altKey
  • event.metaKey(适用于Mac用户的Aka Cmd)

在线样本

---更新后的评论---

您可以做这样的事情

  ngOnInit() {
        this.bindKeypressEvent().subscribe(($event: KeyboardEvent) => this.onKeyPress($event));
    }

    onKeyPress($event: KeyboardEvent) {
        if(($event.ctrlKey || $event.metaKey) && $event.keyCode == 67)
            console.log('CTRL + C');
        if(($event.ctrlKey || $event.metaKey) && $event.keyCode == 86)
            console.log('CTRL +  V');
    }

    private bindKeypressEvent(): Observable<KeyboardEvent> {
        const eventsType$ = [
            fromEvent(window, 'keypress'),
            fromEvent(window, 'keydown')
        ];
        // we merge all kind of event as one observable.
        return merge(...eventsType$)
            .pipe(
                // We prevent multiple next by wait 10ms before to next value.
                debounce(() => timer(10)),
                // We map answer to KeyboardEvent, typescript strong typing...
                map(state => (state as KeyboardEvent))
            );
    }
Run Code Online (Sandbox Code Playgroud)

或者如果不起作用,则:

private bindKeypress(): Observable<KeyboardEvent> {
    const typeOfEvent = this.deviceService.getKeybordEvent();
    fromEvent(window, typeOfEvent)
    .pipe(
        // We map answer to KeyboardEvent, typescript strong typing...
        map(state => (state as KeyboardEvent))
    );
}
Run Code Online (Sandbox Code Playgroud)

this.deviceService.getKeybordEvent();根据用户代理返回事件类型的方法在哪里。大量的用户代理列表可以在这里找到


Tom*_*ula 7

Angular提供高级API,用于收听按键组合.请查看以下示例.

CTRL-keys.directive.ts

import { Directive, Output, EventEmitter, HostListener } from '@angular/core';

@Directive({
  selector: '[ctrlKeys]',
})
export class CtrlKeysDirective  {
  @Output() ctrlV = new EventEmitter();
  @Output() ctrlC = new EventEmitter();

  @HostListener('keydown.control.v') onCtrlV() {
    this.ctrlV.emit();
  }

  @HostListener('keydown.control.c') onCtrlC() {
    this.ctrlC.emit();
  }
}
Run Code Online (Sandbox Code Playgroud)

用法

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <input ctrlKeys (ctrlV)="onCtrlV()" (ctrlC)="onCtrlC()" >
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  onCtrlV() {
    console.log('ctrlV pressed')
  }

  onCtrlC() {
    console.log('ctrlC pressed')
  }
}
Run Code Online (Sandbox Code Playgroud)

现场演示


Dil*_*age 6

只需将其添加到任何组件即可。当用户执行组合键Ctrl +时s,它将打印“保存已执行”

@HostListener('document:keydown.control.s', ['$event']) onKeydownHandler(event: KeyboardEvent) {
    console.log('Save Performed');
    event.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)

如果您想要Ctrl +v将“document:keydown.control.s”中的“s”替换为“v”。