Last active
September 25, 2019 01:29
-
-
Save marcoskubis/fe65b5e1292daa8ba1700f7010d8ffae to your computer and use it in GitHub Desktop.
Ionic 3 input mask directive
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
<ion-input mask='(99) 9999-9999' [(ngModel)]='phone' type='text'></ion-input> |
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, 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires vanilla-masker package.