Limit input field to two decimal places - Angular 5

prajeesh picture prajeesh · Jun 6, 2018 · Viewed 56.7k times · Source

The code is as follows

<input type="number" class="form-control" value="" name="cost_price" #name="ngModel" [(ngModel)]="item.cost_price" placeholder="Cost Price"  />

User should not be able to type more that 2 decimal places.

For example, if the user wants to enter 21.256. He should be only allowed to enter 21.25

How to achieve this using angular 5?

Answer

Sanoj_V picture Sanoj_V · Jun 7, 2018

First create Directive for limit the two decimal places in typescript like this:

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);
    // Allow Backspace, tab, end, and home keys
    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();
    }
  }
}

Inject Directive in your app.module.ts. In your html use that directive like this:

<input type="textbox" [(ngModel)]="InputValue" appTwoDigitDecimaNumber>

Here is working example in Angular 4/5/6: Limit Two decimal places number validation

Hope this will help you!!!!