【发布时间】:2019-12-02 10:38:44
【问题描述】:
我正在尝试创建一个指令,将小数点限制为最多两位。所以当用户输入一个小数时,他最多只能输入两个小数点。 它适用于 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
【问题讨论】:
-
{N} !== 浏览器,没有开箱即用的按键事件,您必须通过在 iOS / text 上扩展委托来本机执行此操作在 Android 上观看听众。
-
你能给我看个样本吗? @Manoj
-
这有点费时。如果您的问题是阻止用户输入无效的输入格式,那么更简单的选择是监听文本更改事件,如果值不符合您的要求,则使用所需值更新文本字段。这对你有用吗?
-
这不是为了防止无效的输入格式。我只想将小数点限制为两位数。 @Manoj
-
即使这样,检查长度/字符并更新文本字段。
标签: angular angularjs-directive nativescript angular2-nativescript nativescript-angular