Categories: Angular

Only Number Input Directive In Angular

In this article, we will create custom directive which allow numbers only 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 only-numbers

Add the following code in your only-numbers directives

import { DOCUMENT } from '@angular/common'
import { Directive, HostBinding, HostListener, Inject } from '@angular/core'

@Directive({
  selector: '[onlyNumbers]',
})
export class OnlyNumbersDirective {
  @HostBinding('autocomplete') public autocomplete

  constructor(@Inject(DOCUMENT) private document: Document) {
    this.autocomplete = 'off'
  }

  @HostListener('keypress', ['$event']) public disableKeys(e: any) {
    this.document.all ? e.keyCode : e.keyCode
    return e.keyCode == 8 || (e.keyCode >= 48 && e.keyCode <= 57)
  }
}

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" onlyNumbers/>
</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