首页 > 解决方案 > 带有小数的数字的角度指令和键盘复制粘贴支持

问题描述

<input type="text" formControlName="reg_retail" appTwoDigitDecimaNumber/>

@Directive({
  selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
  // Allow decimal numbers and negative values
  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = [
    'Backspace',
    'Tab',
    'End',
    'Home',
    '-',
    'ArrowLeft',
    'ArrowRight',
    'Del',
    'Delete'
  ];

  constructor(private el: ElementRef) {}
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [
      current.slice(0, position),
      event.key == 'Decimal' ? '.' : event.key,
      current.slice(position)
    ].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

在这里,我在这种情况下使用反应形式,输入应该允许键盘复制,粘贴支持也只允许 2 位小数。

代码工作正常,就像只在输入中允许 2 个小数点,但如果我复制粘贴一个值,它就不起作用

标签: javascriptangularangularjs-directiveangular-reactive-formsangular-directive

解决方案


推荐阅读