Angular2 - Input Field To Accept Only Numbers

2019-01-08 05:57发布

In Angular2, how can I mask an input field(textbox) such that it accepts only numbers and not alphabets?

I have the following HTML input:

<input type="text" *ngSwitchDefault class="form-control" (change)="onInputChange()" [(ngModel)]="config.Value" focus)="handleFocus($event)" (blur)="handleBlur($event)"/>

The above input is a generic text input which may either be used as a simple text field or as a numeric field, (for example to show the Year).

Using angular2, how can I use the same input control and apply some sort of filter/mask on this field, such that it accepts only numbers? What are the different ways I can achieve this?

Note: I need to achieve this using only textbox and not using input number type.

21条回答
Explosion°爆炸
2楼-- · 2019-01-08 06:36

You need to use type="number" instead text. You can also specify max and min numbers

<input type="number" name="quantity" min="1" max="5">
查看更多
甜甜的少女心
3楼-- · 2019-01-08 06:37
<input type="text" (keypress)="keyPress($event)">


  keyPress(event: any) {
    const pattern = /[0-9\+\-\ ]/;

    let inputChar = String.fromCharCode(event.charCode);
    if (event.keyCode != 8 && !pattern.test(inputChar)) {
      event.preventDefault();
    }
  }
查看更多
Emotional °昔
4楼-- · 2019-01-08 06:38

fromCharCode returns 'a' when pressing on the numpad '1' so this methoid should be avoided

(admin: could not comment as usual)

查看更多
成全新的幸福
5楼-- · 2019-01-08 06:38

you can achive it like this

<input type="text" pInputText (keypress)="onlyNumberKey($event)" maxlength="3"> 

onlyNumberKey(event) {
    return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}

//for Decimal you can use this as

onlyDecimalNumberKey(event) {
    let charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 46 && charCode > 31
        && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

hope this will help you.

查看更多
我只想做你的唯一
6楼-- · 2019-01-08 06:39

A more concise solution. Try this directive.

Can also be used if you're using ReactiveForms.

export class NumberOnlyDirective {
  private el: NgControl;

  constructor(private ngControl: NgControl) {
    this.el = ngControl;
  }

  // Listen for the input event to also handle copy and paste.
  @HostListener('input', ['$event.target.value'])
  onInput(value: string) {
    // Use NgControl patchValue to prevent the issue on validation
    this.el.control.patchValue(value.replace(/[^0-9]/g, ''));
  }
}

The use it on your inputs like this:

<input matInput formControlName="aNumberField" numberOnly>
查看更多
一纸荒年 Trace。
7楼-- · 2019-01-08 06:40

Just use HTML5, input type=”number”

查看更多
登录 后发表回答