Created
November 9, 2017 13:53
-
-
Save dmsysop/7497adefe460fd40928aac0694e95d53 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, HostListener, Input, ElementRef, forwardRef } from '@angular/core'; | |
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; | |
@Directive({ | |
selector: '[inputMask]', | |
providers: [{ | |
provide: NG_VALUE_ACCESSOR, | |
useExisting: InputMaskDirective, | |
multi: true | |
}] | |
}) | |
export class InputMaskDirective implements ControlValueAccessor { | |
constructor(private element: ElementRef) { } | |
onTouched: any; | |
onChange: any; | |
@Input('inputMask') inputMask: string; | |
writeValue(value: any): void { | |
} | |
registerOnChange(fn: any): void { | |
this.onChange = fn; | |
} | |
registerOnTouched(fn: any): void { | |
this.onTouched = fn; | |
} | |
@HostListener('keyup', ['$event']) | |
onKeyup($event: any) { | |
var valor = $event.target.value.replace(/\D/g, ''); | |
var pad = this.inputMask.replace(/\D/g, '').replace(/9/g, '_'); | |
var valorMask = valor + pad.substring(0, pad.length - valor.length); | |
// retorna caso pressionado backspace | |
if ($event.keyCode === 8) { | |
this.onChange(valor); | |
return; | |
} | |
if (valor.length <= pad.length) { | |
this.onChange(valor); | |
} | |
var valorMaskPos = 0; | |
valor = ''; | |
for (var i = 0; i < this.inputMask.length; i++) { | |
if (isNaN(parseInt(this.inputMask.charAt(i)))) { | |
valor += this.inputMask.charAt(i); | |
} else { | |
valor += valorMask[valorMaskPos++]; | |
} | |
} | |
if (valor.indexOf('_') > -1) { | |
valor = valor.substr(0, valor.indexOf('_')); | |
} | |
$event.target.value = valor; | |
} | |
@HostListener('blur', ['$event']) | |
onBlur($event: any) { | |
if ($event.target.value.length === this.inputMask.length) { | |
return; | |
} | |
this.onChange(''); | |
$event.target.value = ''; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment