Last active
July 14, 2021 05:10
-
-
Save zzpmaster/57b9c9f5e3d5ac532d19c6b2384dce9a to your computer and use it in GitHub Desktop.
Transforms a number to a currency string and Currency thousandth format in angular form.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Directive({ | |
selector: '[formControlName][appAmountMask]' | |
}) | |
export class AmountMaskDirective implements OnInit { | |
private hasFocus = false; | |
private element: HTMLInputElement; | |
private digits = '1.0-7'; | |
constructor( | |
private elementRef: ElementRef, | |
private control: NgControl, | |
private decimalPipe: DecimalPipe | |
) {} | |
public ngOnInit(): void { | |
this.element = this.elementRef.nativeElement; | |
} | |
@HostListener('focus', ['$event.target.value']) | |
public onFocus(value: string): void { | |
this.hasFocus = true; | |
this.element.value = this.removeComma(value); | |
} | |
@HostListener('blur', ['$event.target.value']) | |
public onBlur(value: string): void { | |
this.hasFocus = false; | |
const commaValue = | |
parseFloat(value) < 1 && parseFloat(value) > 0 | |
? value | |
: this.decimalPipe.transform(value.trim(), this.digits); | |
if (this.control) { | |
this.control.control.patchValue(value); | |
this.element.value = commaValue; | |
return; | |
} | |
this.element.value = commaValue; | |
const v = this.removeComma(this.element.value); | |
this.control.control.patchValue(v); | |
} | |
private removeComma(target: string): string { | |
return target.replace(/,/g, ''); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment