I am trying to create a directive that will format the input value to a currency format.
I am able to do what I have to do on focus and on blur, and in the ngOnInit hook (and any other hook), the input element does not yet have any values applied to it.
How do I "watch" for the input's value, and format it when it's initial value is applied?
Here is my directive:
import {
Input,
Directive,
HostListener,
ElementRef,
Renderer,
OnInit
} from '@angular/core';
import { NgModel } from '@angular/forms';
import { CurrencyPipe } from '@angular/common';
@Directive({
selector: '[currencyInput]',
providers: [NgModel],
host: {
'(input)': 'onInputChange()'
}
})
export class CurrencyInputDirective implements OnInit {
@Input() ngModel: number;
private elem: HTMLInputElement;
constructor(
private el: ElementRef,
private render: Renderer,
private currencyPipe: CurrencyPipe,
private model: NgModel,
) {
this.elem = el.nativeElement;
}
ngOnInit() {
this.elem.value = this.currencyPipe.transform(parseInt(this.elem.value), 'USD', true);
}
@HostListener('focus', ['$event.target.value'])
onFocus(value: string) {
this.elem.value = value.replace(/\,/g, '');
}
@HostListener('blur', ['$event.target.value'])
onBlur(value: string) {
this.elem.value = this.currencyPipe.transform(parseInt(value), 'USD', true);
}
}