Categories: Angular

Number Only Input In Angular

In this article, we will learn to allow only numbers in the input field.

Step 1:-

Create an Angular application using this command

ng new demo
cd demo

Step 2:-

Create directives using this command

ng generate directive number-only

Add the following code in your number-only directives

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

@Directive({
  selector: '[appNumberOnly]',
})
export class NumberOnlyDirective {
  @Input()
  maxLength!: number

  @Input()
  language!: string

  @Input() isAllowFirstZero = 'false'

  @Input() isDirectiveDisabled = false

  constructor(private element: ElementRef, public model: NgControl) {}

  @HostListener('input', ['$event'])
  onEvent() {
    if (this.isDirectiveDisabled) {
      return
    }
    // let regx = this.language == 'ar' ? '[٠-٩^]' : '[^0-9]';
    let value: string = this.element.nativeElement.value.replace(/[^0-9]/g, '')
    let newVal: any

    if (!value) {
      newVal = undefined
    } else if (value.length > this.maxLength) {
      value = value.slice(0, this.maxLength - value.length)
    }

    newVal = value

    if (newVal && newVal[0] === '0' && this.isAllowFirstZero === 'false') {
      this.model?.control?.setValue('')
    } else {
      this.model?.control?.setValue(newVal)
    }

    if (
      this.isAllowFirstZero === 'true' &&
      value.length >= this.maxLength &&
      /^0*$/.test(newVal.toString())
    ) {
      this.model?.control?.setErrors({ invalid: true })
    }
  }
}

Step 3:-

Add following code to app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

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

  userForm: FormGroup | any

  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      name: ['', Validators.required],
      contactNo: ['', [Validators.required, Validators.minLength(10)]],
    })
  }

  ngOnInit(): void {
  }

}

Step 4:-

Add following code to app.component.html

<form name="artistForm" [formGroup]="userForm">
    <label>Name : </label>
    <input type="text" name="name"  formControlName="name"/>
    <br>
    <label>Contact No : </label>
    <input type="text" name="contactNo"  formControlName="contactNo" appNumberOnly/>
</form>

Step 5:-

npm start
krishna kukadiya

Jr. .Net Developer

Share
Published by
krishna kukadiya

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago