Two Decimal Value Directives In Angular

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

Add the following code in your only-numbers directives

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    console.log(this.el.nativeElement.value);
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

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)]],
      price :['']
    })
  }

  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" />
    <br> 
    <label>Price : </label> 
    <input type="number" name="price" formControlName="price" appTwoDigitDecimaNumber/>
</form>

Step 5:-

npm start

Submit a Comment

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

Subscribe

Select Categories