[英]Allow only numbers in a text input with Angular
I am trying to write code which will allow only numbers in a text input text.我正在尝试编写只允许文本输入文本中的数字的代码。 I've written the following directive.我编写了以下指令。
import { Directive, ElementRef, Input, HostListener } from '@angular/core'
@Directive({
selector: '[appAllowNumberonly]'
})
export class AllowNumberonlyDirective {
private el: HTMLInputElement;
constructor(private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
@HostListener("keydown", ["$event"])
onKeyDown(e: KeyboardEvent) {
if (this.el.value == undefined) {
this.el.value = '';
}
let transformedInput = this.el.value.replace(/[^0-9]/g, '');
if (transformedInput != this.el.value) {
this.el.value = transformedInput;
}
}
@HostListener("keyup", ["$event"])
onKeyUp(e: KeyboardEvent) {
if (this.el.value == undefined) {
this.el.value = '';
e.preventDefault();
}
let transformedInput = this.el.value.replace(/[^0-9]/g, '');
if (transformedInput != this.el.value) {
this.el.value = transformedInput;
}
return transformedInput;
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
if (this.el.value == undefined) {
this.el.value = '';
}
let transformedInput = this.el.value.replace(/[^0-9]/g, '');
if (transformedInput != this.el.value) {
this.el.value = transformedInput;
}
}
}
This works perfectly fine, but user is able to enter value into the text box and then my directive is removing the values that are non-numeric, but I want to stop user from entering into the textbox, how can I achieve that?这工作得很好,但用户能够在文本框中输入值,然后我的指令删除非数字值,但我想阻止用户进入文本框,我该如何实现?
I want to cover copy paste scenario with mouse as well.我也想用鼠标覆盖复制粘贴场景。
I have below Plunker which works perfectly fine in AngularJS (1.x), how do I convert to Angular?我有下面的 Plunker,它在 AngularJS (1.x) 中工作得很好,我如何转换为 Angular? I am unable to use parsers.我无法使用解析器。
http://jsfiddle.net/thomporter/DwKZh/ http://jsfiddle.net/thomporter/DwKZh/
I also tried this:我也试过这个:
Try this directive.试试这个指令。 Listen for the input event to also handle copy and paste.侦听输入事件以处理复制和粘贴。
export class NumberOnlyDirective {
constructor(private el: NgControl) {}
@HostListener('input', ['$event.target.value'])
onInput(value: string) {
// NOTE: use NgControl patchValue to prevent the issue on validation
this.el.control.patchValue(value.replace(/[^0-9]/g, ''));
}
}
You can use Ng Knife utility您可以使用Ng Knife实用程序
Import NgKnifeModule导入 NgKnifeModule
... import { NgKnifeModule } from 'ng-knife'; ... @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, NgKnifeModule ], ... }); export class AppModule { }
Using it:使用它:
<!-- Only Numbers --> <input knifeOnlyNumbers type="text">
your directive code should have this你的指令代码应该有这个
@HostListener("keypress",['$event']) onKeyPress(e){
var char=e.char;
var regExp = new RegExp(/[0-9.]/);
if (regExp.test(char))
return true
else
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.