Last active
February 9, 2020 23:06
-
-
Save Kyoss79/b8ee0c61a216064862fc58e1f1126e35 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 (Original Discussion found here: https://github.com/text-mask/text-mask/issues/109)
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, 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