Last active
November 24, 2017 20:14
-
-
Save johnatans/0b96dac6ca923d559e988f4f8c786533 to your computer and use it in GitHub Desktop.
Directive - Soluction for Mask input in ionic/angular 4
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
| <ion-input type="tel" pattern="\d*" placeholder="(xxx) xxx-xxxx" mask="(***) ***-****" [(ngModel)]="phone" name="phone"></ion-input> |
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/forms'; | |
| @Directive({ | |
| selector: '[mask]', | |
| host: { '(keyup)': 'onInputChange($event)' }, | |
| providers: [NgModel] | |
| }) | |
| export class InputMask { | |
| public pattern: string; | |
| constructor(public model: NgModel, @Attribute('mask') pattern: string) { | |
| this.pattern = pattern; | |
| } | |
| onInputChange(event) { | |
| let value = event.target.value, | |
| pattern = this.pattern; | |
| if (event.keyIdentifier === 'U+0008' || event.keyCode === 8 || event.key === 'Backspace') { | |
| if (value.length) { | |
| while (pattern[value.length] && pattern[value.length] !== '*') { | |
| value = value.substring(0, value.length - 1); | |
| } | |
| // remove toda a formatação principal para restaurar o marcador de posição | |
| if (pattern.substring(0, value.length).indexOf('*') < 0) { | |
| value = value.substring(0, value.length - 1); | |
| } | |
| } | |
| } else { | |
| let maskIndex = value.length, | |
| formatted = ''; | |
| if (value.length === 1 && value !== pattern[0]) { | |
| // aplicando a formatação principal | |
| maskIndex = 0; | |
| while (maskIndex < pattern.length && pattern[maskIndex] !== '*') { | |
| formatted += pattern[maskIndex]; | |
| maskIndex++; | |
| } | |
| } | |
| formatted += value; | |
| if (maskIndex < pattern.length) { | |
| // aplicando formatação final | |
| while (pattern[maskIndex] !== '*') { | |
| formatted += pattern[maskIndex]; | |
| maskIndex++; | |
| } | |
| } | |
| value = formatted; | |
| } | |
| this.model.update.emit(value); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment