简体   繁体   English

只允许在带有 Angular 的文本输入中输入数字

[英]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实用程序

  1. Import NgKnifeModule导入 NgKnifeModule

     ... import { NgKnifeModule } from 'ng-knife'; ... @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, NgKnifeModule ], ... }); export class AppModule { }
  2. 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.

相关问题 Angular 2/4 需要一个 Typescript 正则表达式来只允许将数字输入到输入文本框中 - Angular 2/4 need a Typescript regex to only allow numbers to be entered into input textbox 如何使用TypeScript只允许html输入类型文本中的数字? - How to allow only numbers in html input type text using TypeScript? 仅在 Angular 中输入数字 - Numbers only Input in Angular Angular - 文本输入字段只接受手机中的数字 - Angular -Text Input Field To Accept Only Numbers in Mobile Phones 在 angular 5 文本框中只允许负数 - allow only negative numbers in angular 5 textbox 在角形材料2输入字段中仅允许数字TAB,DELETE,BACKSPACE,向左箭头,向右箭头 - allow only numbers, TAB , DELETE, BACKSPACE, Left Arrow, Right Arrow in angular material 2 input field 角度反应形式模式验证器只允许文本、数字和一些字符 - angular reactive form pattern validator only allow text, numbers and some characters 如何创建角度指令文本框只允许数字空格和分数 - How to create angular directive text box only allow numbers space and fraction 允许在on之前和之后使用十进制数和限制数<input type="“text”"> - Allow decimal numbers and limit numbers before and after on <input type=“text”> 带空格的输入字段只不允许保存角度? - Input field with spaces only not allow to save in angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM