Skip to content

Instantly share code, notes, and snippets.

@Kyoss79
Created July 26, 2019 14:38
Show Gist options
  • Save Kyoss79/7a86bc35f22b9b520579724331e0173b to your computer and use it in GitHub Desktop.
Save Kyoss79/7a86bc35f22b9b520579724331e0173b to your computer and use it in GitHub Desktop.
Working example of a directive, that converts input fields which have been masked with textMask to a valid number in the ngModel
import { Directive, ElementRef, HostListener, Output, EventEmitter } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[numeric]'
})
export class NumericDirective {
@Output() ngModelChange: EventEmitter<any> = new EventEmitter<any>(false);
constructor(
private elementRef: ElementRef,
private model: NgControl
) {
}
@HostListener('input') inputChange() {
const newValue = this.unMask();
if (newValue) {
this.model.control.setValue(newValue, {
emitEvent: true, // this is really weird, since it's NOT recommended in the github comment
emitModelToViewChange: false,
emitViewToModelChange: false
});
}
}
@HostListener('focusout') onFocusout() {
this.ngModelChange.emit(this.unMask());
}
unMask() {
const elementValue = this.elementRef.nativeElement.value;
if (elementValue) {
// TODO: this needs to be adjusted depending on the LOCALE
return Number(elementValue.replace(/[^\d,-]/g, '', ''));
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment