Created
December 19, 2019 16:52
-
-
Save kievsash/71c7d70652bf7a6b09e0d8988fbdc8fd to your computer and use it in GitHub Desktop.
matInput commified
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
//html | |
<input formControlName="account_value" | |
appCommified | |
matInput type="text"> | |
//typescript | |
import {Directive, ElementRef, HostListener, Input} from '@angular/core'; | |
import {MAT_INPUT_VALUE_ACCESSOR} from '@angular/material'; | |
import {numberWithCommas} from '@app/global_helpers'; | |
@Directive({ | |
selector: 'input[appCommified]', | |
providers: [ | |
{provide: MAT_INPUT_VALUE_ACCESSOR, useExisting: CommifiedDirective}, | |
] | |
}) | |
export class CommifiedDirective { | |
private _value: string | null; | |
constructor(private _elementRef: ElementRef<HTMLInputElement>, | |
) { | |
setTimeout(() => { | |
const value = this._elementRef.nativeElement.value | |
this._formatValue(value) | |
}, 30) | |
} | |
get value(): string | null { | |
console.log('get Value'); | |
return this._value | |
} | |
@Input('value') | |
set value(value: string | null) { | |
console.log('set Value', value); | |
this._value = value; | |
this._formatValue(value) | |
} | |
private _formatValue(value: string | null) { | |
console.log('_formatValue', value); | |
if (value !== null) { | |
this._elementRef.nativeElement.value = numberWithCommas(value); | |
} else { | |
this._elementRef.nativeElement.value = ''; | |
} | |
} | |
private unFormatValue() { | |
const value = this._elementRef.nativeElement.value; | |
this._value = value.replace(/[^0-9]/g, ''); | |
console.log('_formatValue', value); | |
if (value) { | |
this._elementRef.nativeElement.value = this._value; | |
} else { | |
this._elementRef.nativeElement.value = ''; | |
} | |
} | |
@HostListener('input', ['$event.target.value']) | |
onInput(value) { | |
console.log('onInput', value); | |
this._value = value.replace(/[^0-9]/g, ''); | |
} | |
@HostListener('blur') | |
_onBlur() { | |
console.log('_onBlur', this._value); | |
if (this._value) { | |
this._formatValue(this._value); | |
} | |
} | |
@HostListener('focus') | |
onFocus() { | |
this.unFormatValue() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment