Created
July 26, 2019 14:38
-
-
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
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