I got a solution using @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; } }
And Pipe Extends 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);
Import Directive for your component
import { CurrencyFormatterDirective } from '../../shared/directive/showOnRowHover'; import { CurrencyPipe } from '../../shared/pipe/orderby'; providers: [CurrencyPipe, CurrencyFormatterDirective]
And the directive on your html input
<input type="text" [(ngModel)]="invoiceDetail.InvoiceAmount" class="form-control" placeholder="Enter invoice amount" CurrencyFormatter>