我只允许输入一个输入数字,还可以输入1个逗号和2个小数。
正确输入的示例:
123
123,22
我已经尝试过在网上找到的该指令,但允许我输入以下字符:`,´,+
指令代码:
import { Directive,ElementRef,HostListener } from '@angular/core';
@Directive({
selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimalNumberDirective {
// 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) {
console.log(this.el.nativeElement.value);
// Allow Backspace,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();
}
}
}
此代码有什么问题?
谢谢