javascript - 带有小数的数字的角度指令和键盘复制粘贴支持
问题描述
<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 个小数点,但如果我复制粘贴一个值,它就不起作用
解决方案
推荐阅读
- powershell - Windows 更新 API CopyToCache(IStringCollection) - 指定的转换无效
- reactjs - 在 iOS 设备上的 React 应用程序中断应用程序中的正则表达式负向后追溯
- python - 如何使用 Python 或 PowerBI 中的给定数据集制作以下图表
- python - 具有权重和类型相关节点和边的网络图
- php - 试图获取非对象的属性“approval_code”
- javascript - 从 HTML 视图解析反应道具以反应组件
- android - android antmedia webrtc 将摄像头切换到屏幕共享,反之亦然
- json - Power Bi - 更改 Web 请求中使用的参数值(api + json)
- azure - 在 Docker 上提高 Azure 计算机视觉的性能
- php - 空值而不是 CodeIgniter 中的值