nativescript-angular-未定义KeyboardEvent

问题描述 投票:2回答:1

我正在尝试创建一个将小数点限制为最多两个的指令。因此,当用户输入一个十进制数字时,他最多只能输入两个小数点。它适用于Angular,但不适用于Nativescript Angular。

这是我创建的指令:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[nsTwoDecimalPlaceLimit]'
})
export class TwoDecimalPlaceLimitDirective {

  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  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();
    }
  }
}

HTML部分如下所示:

    <StackLayout class="form">
        <TextField class="m-5 input input-border" hint="Disabled" nsTwoDecimalPlaceLimit>
        </TextField>
    </StackLayout>

运行此命令时,出现以下错误:

ERROR Error: Uncaught (in promise): ReferenceError: KeyboardEvent is not defined

这里是一个Playground Sample

angular angularjs-directive nativescript angular2-nativescript nativescript-angular
1个回答
2
投票

政府回答

https://github.com/angular/universal/issues/830#issuecomment-345228799

您必须在node_modules中进行更改

angular-universal-starter/blob/master/server.ts

替换它

global['KeyboardEvent'] = win.Event;

也请检查此内容

Angular Universal ReferenceError - KeyboardEvent is not defined

© www.soinside.com 2019 - 2024. All rights reserved.