[英]Allow only one decimal and only positive number in Angular
I have tried below code but it doesn't seem to be the perfect solution.我试过下面的代码,但它似乎不是完美的解决方案。 Also, the keypress event does not work on mobile.
此外,按键事件在移动设备上不起作用。 I have tested on android google chrome.
我已经在 android google chrome 上测试过。 Please help if there is any perfect solution.
如果有任何完美的解决方案,请帮助。
In HTML file I added keypress event.在 HTML 文件中,我添加了按键事件。
<input type="text" name="xyz"(keypress)="numberOnlyWithDecimal($event,xyz)"[(ngModel)]="xyz">
In .ts file, I added this code.在 .ts 文件中,我添加了此代码。
numberOnlyWithDecimal(event, text): boolean {
var regex = /^\d+(\.\d+)?$/;
const charCode = (event.which) ? event.which : event.keyCode;
if (text) {
var test = text.split(".")
this.textLength = test.length - 1;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (!regex.test(charCode)) {
return false
}
if (charCode == 46 && this.textLength ==1 ) {
return false
}
return true;
}
You can use Directive to implement that.您可以使用Directive来实现它。
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appInputOnlyDecimal]'
})
export class InputOnlyDecimalDirective {
constructor(private ngControl: NgControl) {}
@HostListener('input', ['$event.target.value'])
public onInput(value: string) {
// Your logic here
}
}
I think something like this should do:我认为这样的事情应该做:
input type="number" min="0" max="9"
输入类型="数字" min="0" max="9"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.