Last active
July 1, 2019 14:08
-
-
Save ihorbond/51768559d01949b09d2aef646fcebe06 to your computer and use it in GitHub Desktop.
Angular 4 decimal directive
This file contains hidden or 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
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