-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: Entering letter, NaN is shown, unable to enter a number
- Loading branch information
1 parent
7ca451a
commit 54b54c4
Showing
3 changed files
with
30 additions
and
9 deletions.
There are no files selected for viewing
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
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
28 changes: 20 additions & 8 deletions
28
packages/angular-sdk-components/src/lib/_directives/thousand-seperator.directive.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,31 @@ | ||
import { Directive, ElementRef, HostListener } from '@angular/core'; | ||
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; | ||
|
||
@Directive({ | ||
selector: '[appThousandSeparator]', | ||
standalone: true | ||
}) | ||
export class ThousandSeparatorDirective { | ||
constructor(private el: ElementRef) {} | ||
constructor(private _inputEl: ElementRef) {} | ||
|
||
@HostListener('input', ['$event']) | ||
onInput(event) { | ||
const input = this.el.nativeElement as HTMLInputElement; | ||
let value: any = input.value.replace(/,/g, ''); // Remove existing commas | ||
if (event?.data !== '.') { | ||
value = Number(value).toLocaleString(); // Add thousands separator | ||
input.value = value; | ||
onInput() { | ||
if (this._inputEl.nativeElement.value === '-') return; | ||
const commasRemoved = this._inputEl.nativeElement.value.replace(/,/g, ''); | ||
let toInt: number; | ||
let toLocale: string; | ||
if (commasRemoved.split('.').length > 1) { | ||
// eslint-disable-next-line no-restricted-globals | ||
const decimal = isNaN(parseInt(commasRemoved.split('.')[1], 10)) ? '' : parseInt(commasRemoved.split('.')[1], 10); | ||
toInt = parseInt(commasRemoved, 10); | ||
toLocale = `${toInt.toLocaleString('en-US')}.${decimal}`; | ||
} else { | ||
toInt = parseInt(commasRemoved, 10); | ||
toLocale = toInt.toLocaleString('en-US'); | ||
} | ||
if (toLocale === 'NaN') { | ||
this._inputEl.nativeElement.value = ''; | ||
} else { | ||
this._inputEl.nativeElement.value = toLocale; | ||
} | ||
} | ||
} |