-
-
Save RodolfoSilva/a76eea8fc0b65636f1691d007792b9f0 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, Attribute} from '@angular/core'; | |
import {NgModel} from '@angular/common'; | |
@Directive({ | |
selector: '[mask]', | |
host: { | |
'(keyup)': 'onInputChange()' | |
} | |
}) | |
export class Mask { | |
maskPattern: string; | |
placeHolderCounts: number; | |
dividers: string[]; | |
modelValue: string; | |
viewValue: string; | |
constructor( | |
public model: NgModel, | |
@Attribute("mask") maskPattern: string | |
) { | |
this.dividers = maskPattern.replace(/\*/g, "").split(""); | |
this.dividers.push(" "); | |
this.generatePattern(maskPattern); | |
} | |
onInputChange() { | |
this.modelValue = this.getModelValue(); | |
var stringToFormat = this.modelValue; | |
if (stringToFormat.length < 10) { | |
stringToFormat = this.padString(stringToFormat); | |
} | |
this.viewValue = this.format(stringToFormat); | |
this.model.viewToModelUpdate(this.modelValue); | |
this.model.valueAccessor.writeValue(this.viewValue) | |
} | |
generatePattern(patternString) { | |
this.placeHolderCounts = (patternString.match(/\*/g) || []).length; | |
for (let i = 0; i < this.placeHolderCounts; i++) { | |
patternString = patternString.replace('*', "{" + i + "}"); | |
} | |
this.maskPattern = patternString; | |
} | |
format(s) { | |
var formattedString = this.maskPattern; | |
for (let i = 0; i < this.placeHolderCounts; i++) { | |
formattedString = formattedString.replace("{" + i + "}", s.charAt(i)); | |
} | |
return formattedString; | |
} | |
padString(s) { | |
var pad = " "; | |
return (s + pad).substring(0, pad.length); | |
} | |
getModelValue() { | |
var modelValue = this.model.value; | |
for (var i = 0; i < this.dividers.length; i++) { | |
while (modelValue.indexOf(this.dividers[i]) > -1) { | |
modelValue = modelValue.replace(this.dividers[i], ""); | |
} | |
} | |
return modelValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment