4

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

4
  • Why not simply use <input type="number" [(ngModel)]="value" ...? Commented Dec 1, 2019 at 9:31
  • 1
    @AndreElrico you can also use e and decimal seperators for example. He only wants digits Commented Dec 1, 2019 at 9:33
  • I've edited my answer. Just wanted to show that there is a little bit shorter way to allow only digits. Commented Dec 1, 2019 at 19:35
  • Does this answer your question? Angular2 - Input Field To Accept Only Numbers Commented Dec 2, 2019 at 12:39

3 Answers 3

7

You can allow only numbers by checking their code:

<input type="number" 
    (keypress)="($event.charCode >= 48 && $event.charCode < 58)"/>
Sign up to request clarification or add additional context in comments.

2 Comments

He only wants digits, type number also allows the e and decimal seperators
@MoxxiManagarm you are right! Sorry, I was hurry, misunderstood requirements!:) I've edited my answer.
4

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

Comments

1

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

1 Comment

Thank you. This alo worked. Please check the correction made by Ashot Aleqsanyan in the code. Now there are 2 ways to do it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.