Create an Angular directive known as TwoDigitDecimalDirective. You can create it manually or using the ng generate directive directive_name or ng g d directive_name command.

If you create the directive manually, you will have to import/inject the directive into the application on your own.

If you create it using the ng command, the directive will be imported into the application automatically.

Angular Directive to Display Numbers with 2 Decimal Places

import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appTwoDigitDecimal]' }) export class TwoDigitDecimalDirective { 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; } const 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(); } } }
Code language: JavaScript (javascript)

How to use TwoDigitDecimalDirective in Reactive Forms

Here is a sample code showing how to use the directive. As you may see in the directive, the selector is appTwoDigitDecimal.

In your form input, place the directive selector as shown below:

<input type="text" class="form-control" formControlName="someNumber"appTwoDigitDecimal>
Code language: JavaScript (javascript)

Leave a Reply

Scroll to Top