将输入字段限制为两位小数 - Angular 5 [英] Limit input field to two decimal places - Angular 5
本文介绍了将输入字段限制为两位小数 - Angular 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码如下
<input type="number" class="form-control" value="" name="cost_price" #name="ngModel" [(ngModel)]="item.cost_price" placeholder="Cost Price" />
用户不能输入超过 2 个小数位.
User should not be able to type more that 2 decimal places.
例如,如果用户想输入 21.256.他应该只被允许进入21.25
For example, if the user wants to enter 21.256. He should be only allowed to enter 21.25
如何使用 angular 5 实现这一点?
How to achieve this using angular 5?
推荐答案
首先创建指令来限制打字稿中的两位小数,如下所示:
First create Directive for limit the two decimal places in typescript like this:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
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) {
console.log(this.el.nativeElement.value);
// 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();
}
}
}
在您的 app.module.ts
中注入指令.在您的 html 中使用该指令,如下所示:
Inject Directive in your app.module.ts
.
In your html use that directive like this:
<input type="textbox" [(ngModel)]="InputValue" appTwoDigitDecimaNumber>
这是 Angular 4/5/6 中的工作示例:限制小数点后两位号码验证
Here is working example in Angular 4/5/6: Limit Two decimal places number validation
希望对你有帮助!!!!
Hope this will help you!!!!
这篇关于将输入字段限制为两位小数 - Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文