import {Directive, OnInit, ElementRef, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[decimal-input]', host: { '(input)': 'onInputChange()' } }) export class DecimalInputDirective implements OnInit { private COMPONENT_NAME: string = 'DecimalInputDirective'; // need to fire this event to update the model @Output() ngModelChange: EventEmitter = new EventEmitter(false); private el: HTMLInputElement; constructor(private elementRef: ElementRef) { this.el = this.elementRef.nativeElement; } ngOnInit() { const METHOD_NAME: string = 'ngOnInit()'; this.el.value = this.formatDecimal(this.el.value); } onInputChange() { const METHOD_NAME: string = 'onInputChange()'; const val = this.el.value; this.el.value = val.replace(/[^0-9]/g, ''); const newVal = this.formatDecimal(val); this.el.value = newVal; // fire model change to update the value this.ngModelChange.emit(this.el.value); } formatDecimal(value): string { const METHOD_NAME: string = 'formatDecimal()'; if (value.length === 0) { return ''; } const n: string = value.replace('.', ''); let newValue = parseInt(n).toString(); while (newValue.length < 3) { newValue = '0' + newValue; } return newValue.substr(0, newValue.length - 2) + '.' + newValue.substr(newValue.length - 2, newValue.length - 1); } }