Alphabets Only In Angular

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

Add the following code in your only-alphabets directives

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

@Directive({
  selector: '[onlyAlphabets]',
})
export class OnlyAlphabetsDirective {
  @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 >= 97 && e.keyCode <= 122) ||
      (e.keyCode >= 65 && e.keyCode <= 90)
    )
  }
}

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" onlyAlphabets/>
    <br>
    <label>Contact No : </label>
    <input type="text" name="contactNo"  formControlName="contactNo"/>
</form>

Step 5:-

npm start

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories