Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Frozen-byte/5ae3a88a2cf0acd149a6adf4a230ecca to your computer and use it in GitHub Desktop.
Save Frozen-byte/5ae3a88a2cf0acd149a6adf4a230ecca to your computer and use it in GitHub Desktop.
Angular2+ GermanNumberDirective
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