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

时间:2018-04-19 12:03:29

标签: angular directive keyboard-events onkeydown

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

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

5 个答案:

答案 0 :(得分:6)

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

<强>用法

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')
  }
}

Live demo

答案 1 :(得分:5)

您只需执行以下操作:获取信息此代码管理用户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');
}

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

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

Online sample

---评论后更新---

你可以做这样的事情

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

或者如果不起作用,只需:

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

其中this.deviceService.getKeybordEvent();是返回用户代理的事件类型的方法。 massive list of user agent can be find here

答案 2 :(得分:2)

我建议不要监控复制和粘贴命令的关键事件,而是处理剪贴板事件(class PaywallHelper { static let sharedDefaults = UserDefaults.init(suiteName: "group.Myapp")! var tokenForPaywall: String? { get { return PaywallHelper.sharedDefaults.string(forKey: "user_token") } set { PaywallHelper.sharedDefaults.setValue(newValue, forKey: "user_token") PaywallHelper.sharedDefaults.synchronize() } } var ad_id: Int? { get { return PaywallHelper.sharedDefaults.integer(forKey: "id") } set { PaywallHelper.sharedDefaults.setValue(newValue, forKey: "id") PaywallHelper.sharedDefaults.synchronize() } } var category_id: Int? { get { return PaywallHelper.sharedDefaults.integer(forKey: "category_id") } set { PaywallHelper.sharedDefaults.setValue(newValue, forKey: "category_id") PaywallHelper.sharedDefaults.synchronize() } } copycut)。除了处理在不同平台上使用的各种快捷方式之外,它还检测使用上下文菜单启动的剪贴板操作。请注意paste事件可以paste取消。您可以在this stackblitz中看到代码正常工作。

e.preventDefault()

答案 3 :(得分:1)

首先导入HostListener并创建方法以侦听keyup事件。 还要使用ctrlKey,因为键码已弃用。

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

    @HostListener('window:keyup', ['$event'])
       keyEvent(event: KeyboardEvent) {
          if (event.ctrlKey) {
              if (event.key === 'c') {
                 console.log('ctrl c');         
              }      
             else if (event.key === 'v') {
                 console.log('ctrl v')
              }
      }

答案 4 :(得分:0)

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

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

如果要 Ctrl + v 用'v'替换'document:keydown.control.s'中的's'。