Angular2 - Input Field To Accept Only Numbers

Question

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.


Show source
| html   | angularjs   | input   | angularjs-directive   | angular2   2017-01-04 14:01 3 Answers

Answers ( 3 )

  1. 2017-01-04 14:01

    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">
    
  2. 2017-01-05 08:01

    You can use angular2 directives. Plunkr

    import { Directive, ElementRef, HostListener, Input } from '@angular/core';
    
    @Directive({
      selector: '[OnlyNumber]'
    })
    export class OnlyNumber {
    
      constructor(private el: ElementRef) { }
    
      @Input() OnlyNumber: boolean;
    
      @HostListener('keydown', ['$event']) onKeyDown(event) {
        let e = <KeyboardEvent> event;
        if (this.OnlyNumber) {
          if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
            // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
            // Allow: Ctrl+X
            (e.keyCode == 88 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
              // let it happen, don't do anything
              return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
          }
      }
    }
    

    and you need to write the directive name in your input as attribute

    <input OnlyNumber="true" />
    

    don't forget to write your directive in declarations array of your module.

    By using regex you would still need functional keys

    export class OnlyNumber {
    
      regexStr = '^[0-9]*$';
      constructor(private el: ElementRef) { }
    
      @Input() OnlyNumber: boolean;
    
      @HostListener('keydown', ['$event']) onKeyDown(event) {
        let e = <KeyboardEvent> event;
        if (this.OnlyNumber) {
            if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
            // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
            // Allow: Ctrl+X
            (e.keyCode == 88 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
              // let it happen, don't do anything
              return;
            }
          let ch = String.fromCharCode(e.keyCode);
          let regEx =  new RegExp(this.regexStr);    
          if(regEx.test(ch))
            return;
          else
             e.preventDefault();
          }
      }
    }
    
  3. 2017-01-05 08:01

    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.

◀ Go back