Ashish
Ashish

Reputation: 469

Numbers only Input in Angular

I am trying to implement an input field, where only number keys are allowed. For that I have successfully implemented the Numbers only validation in Forms.

But here the requirement is that no other keys should work except the number keys. For that I have tied to implement a @HostListener

In this case, when we click on alphabet keys, it does not show in the input field, but the value get assigned which that alphabet.

Please check the code: HostListener code:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: 'input[numbersOnly]'
})
export class NumberDirective {

  constructor(private _el: ElementRef) { }

  @HostListener('input', ['$event']) onInputChange(event) {
    const initalValue = this._el.nativeElement.value;
    this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
    if ( initalValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }

}

HTML :

Type anything other than numbers, the change is fired even if the textfield content does not change :
<br/>
<input type="text" [(ngModel)]="value" (ngModelChange)="onChange($event)" numbersOnly/>
<br/>
Change fire counter : {{counter}}
<br>
Value = {{value}}

TS file :

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  value='';
  counter = 0;

  onChange(event) {
    this.counter = this.counter + 1; 
  }
}

so see the actual code running please click on : https://stackblitz.com/edit/angular-numbers-only-directive-tb66et

enter image description here

PLEASE HELP. The intention is that the value should not have only number characters.

Regards, Ashish

Upvotes: 4

Views: 25375

Answers (3)

StepUp
StepUp

Reputation: 38199

You can allow only numbers by checking their code:

<input type="number" 
    (keypress)="($event.charCode >= 48 && $event.charCode < 58)"/>

Upvotes: 7

MoxxiManagarm
MoxxiManagarm

Reputation: 9134

You could try with keydown event in the directive as explained here

https://codeburst.io/digit-only-directive-in-angular-3db8a94d80c3

Also used here:

Angular2 - Input Field To Accept Only Numbers

Upvotes: 1

Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

Look your regexp is correct and when you console the value in onChange the value is correct. The only problem is that it doesn’t display correctly, I tried to manually update it manually with DetectionRef.detectChanges but it did not help. I did what you need but in little different way please look on .html and directive https://stackblitz.com/edit/angular-numbers-only-directive-xttsje

Upvotes: 4

Related Questions