Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 793
Ashish Avatar asked Oct 25 '25 01:10

Ashish


2 Answers

You can allow only numbers by checking their code:

<input type="number" 
    (keypress)="($event.charCode >= 48 && $event.charCode < 58)"/>
like image 163
StepUp Avatar answered Oct 26 '25 17:10

StepUp


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

like image 41
Ashot Aleqsanyan Avatar answered Oct 26 '25 15:10

Ashot Aleqsanyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!