Created
July 7, 2018 14:06
-
-
Save Frozen-byte/5ae3a88a2cf0acd149a6adf4a230ecca to your computer and use it in GitHub Desktop.
Angular2+ GermanNumberDirective
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
import { Directive, ElementRef, forwardRef, HostListener, Optional, Renderer2 } from "@angular/core"; | |
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NgModel } from "@angular/forms"; | |
export const GERMAN_NUMBER_VALUE_ACCESSOR: any = { | |
// multi: true, | |
provide: NG_VALUE_ACCESSOR, | |
useExisting: forwardRef(() => NxGermanNumberDirective), | |
}; | |
@Directive({ | |
providers: [GERMAN_NUMBER_VALUE_ACCESSOR], | |
selector: "input[formControl][nxGermanNumber]", // TODO NX-??? input[ngModel][nxGermanNumber] | |
}) | |
export class NxGermanNumberDirective implements ControlValueAccessor { | |
public onChange: (value: string) => void = () => { | |
}; | |
public onTouched: () => void = () => { | |
}; | |
constructor( | |
private renderer: Renderer2, | |
private elementRef: ElementRef, | |
) { | |
} | |
@HostListener("input", ["$event.target.value"]) | |
@HostListener("change", ["$event.target.value"]) | |
public applyChange(value: string): void { | |
this.onChange(value); | |
} | |
@HostListener("blur") | |
public applyTouched(): void { | |
this.onTouched(); | |
} | |
public registerOnChange(fn: (_: number | null) => void): void { | |
this.onChange = (value) => { | |
const numberValue = value === "" ? null : this.toNumber(value); | |
fn(numberValue); | |
this.renderer.setProperty(this.elementRef.nativeElement, "value", value); | |
}; | |
} | |
public registerOnTouched(fn: () => void): void { | |
this.onTouched = () => { | |
const displayValue = this.toNumber(this.elementRef.nativeElement.value); | |
fn(); | |
this.writeValue(isNaN(displayValue) ? "" : displayValue); | |
}; | |
} | |
public setDisabledState(isDisabled: boolean): void { | |
this.renderer.setProperty(this.elementRef.nativeElement, "disabled", isDisabled); | |
} | |
public writeValue(value: string | number): void { | |
if (typeof value === "number") { | |
value = value.toLocaleString("de-DE"); | |
} | |
this.renderer.setProperty(this.elementRef.nativeElement, "value", value); | |
} | |
private toNumber(value: string): number { | |
return parseFloat(value | |
.replace(/[^\d\-,]/g, "") | |
.replace(",", ".")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment