Skip to content

Instantly share code, notes, and snippets.

@mhartington
Created May 24, 2016 18:28
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mhartington/3279ce8ef7bf68bc5e3442203c32ec86 to your computer and use it in GitHub Desktop.
Save mhartington/3279ce8ef7bf68bc5e3442203c32ec86 to your computer and use it in GitHub Desktop.
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;
}
}
@lu1tr0n
Copy link

lu1tr0n commented Jun 4, 2020

Hello @mhartington, this code works for ionic 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment