Skip to content

Instantly share code, notes, and snippets.

@kievsash
Created December 19, 2019 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kievsash/71c7d70652bf7a6b09e0d8988fbdc8fd to your computer and use it in GitHub Desktop.
Save kievsash/71c7d70652bf7a6b09e0d8988fbdc8fd to your computer and use it in GitHub Desktop.
matInput commified
//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