Skip to content

Instantly share code, notes, and snippets.

@marcoskubis
Last active September 25, 2019 01:29
Show Gist options
  • Save marcoskubis/fe65b5e1292daa8ba1700f7010d8ffae to your computer and use it in GitHub Desktop.
Save marcoskubis/fe65b5e1292daa8ba1700f7010d8ffae to your computer and use it in GitHub Desktop.
Ionic 3 input mask directive
<ion-input mask='(99) 9999-9999' [(ngModel)]='phone' type='text'></ion-input>
import { Directive, Attribute } from '@angular/core';
import { NgModel } from '@angular/forms';
import * as masker from 'vanilla-masker';
@Directive({
selector: '[mask]',
host: {
'(keyup)': 'onInputChange($event)',
},
providers: [NgModel]
})
export class MaskDirective {
pattern: string;
constructor(
public model: NgModel,
@Attribute('mask') pattern: string
) {
this.pattern = pattern;
}
onInputChange(event) {
let value = event.target.value;
let pattern = this.pattern;
if (value.length > this.pattern.length) {
value = value.substring(0, this.pattern.length);
}else{
value = masker.toPattern(value, pattern);
}
this.model.update.emit(value);
}
}
@marcoskubis
Copy link
Author

Requires vanilla-masker package.

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