我正在尝试创建一个将小数点限制为最多两个的指令。因此,当用户输入一个十进制数字时,他最多只能输入两个小数点。它适用于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
在政府回答
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