I successfully implemented a solution with the help of @pipe
import { Directive, Input, Inject, HostListener, ElementRef, OnInit } from "@angular/core";
const PADDING = "000000";
@Pipe({ name: "CurrencyPipe" })
export class CurrencyPipe implements PipeTransform {
transform(value: any, args: string[]): any {
var clean = value.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if (negativeCheck[1] != undefined) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + '-' + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}
}
if (decimalCheck[1] != undefined) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
return clean;
}
parse(value: string, fractionSize: number = 2): string {
var clean = value.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if (negativeCheck[1] != undefined) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + '-' + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}
}
if (decimalCheck[1] != undefined) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
return clean;
}
}
Additionally, I utilized this Pipe Extension in my directive.
import { Directive, Input, Inject, HostListener, OnChanges, ElementRef, Renderer, AfterViewInit, OnInit } from "@angular/core";
import { CurrencyPipe } from '../../shared/pipe/orderby';
@Directive({ selector: "[CurrencyFormatter]" })
export class CurrencyFormatterDirective {
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private currencyPipe: CurrencyPipe
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.el.value = this.currencyPipe.parse(this.el.value);
}
@HostListener("focus", ["$event.target.value"])
onFocus(value) {
this.el.value = this.currencyPipe.parse(value); // opposite of transform
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
this.el.value = this.currencyPipe.parse(value);
}
@HostListener("keyup", ["$event.target.value"])
onKeyUp(value) {
this.el.value = this.currencyPipe.parse(value);
}
}
Remember to import the Directive in your component
import { CurrencyFormatterDirective } from '../../shared/directive/showOnRowHover';
import { CurrencyPipe } from '../../shared/pipe/orderby';
providers: [CurrencyPipe,
CurrencyFormatterDirective]
Lastly, add the Directive to your html Input
<input type="text" [(ngModel)]="invoiceDetail.InvoiceAmount" class="form-control" placeholder="Enter invoice amount"
CurrencyFormatter>