Skip to content

Instantly share code, notes, and snippets.

@ihorbond
Last active July 1, 2019 14:08
Show Gist options
  • Save ihorbond/51768559d01949b09d2aef646fcebe06 to your computer and use it in GitHub Desktop.
Save ihorbond/51768559d01949b09d2aef646fcebe06 to your computer and use it in GitHub Desktop.
Angular 4 decimal directive
import { Input, Directive, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";
import { DecimalPipe } from "@angular/common";
/*
* Form control decimal directive.
* Pass optional custom regex and pipe expression.
* */
@Directive({
selector: '[decimalPipe]'
})
export class FormControlDecimalPipeDirective {
@Input() precision: number = 2;
@Input() regex: RegExp = null;
@Input() pipeExp: string = `1.${this.precision}-${this.precision}`;
constructor(
protected _ngControl: NgControl
) { }
@HostListener('focusout', ['$event'])
protected onBlur(event: FocusEvent) {
const value = this._ngControl.value;
if (this.regex && !this.regex.test(value)) {
this._ngControl.control.patchValue(null);
}
else {
this.transformValue(value);
}
}
protected transformValue(value: any): void {
try {
const pipe = new DecimalPipe('en');
const formatted = pipe.transform(value, this.pipeExp).replace(/,/g, '');
this._ngControl.control.patchValue(formatted);
}
catch (err) {
this._ngControl.control.patchValue(null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment