Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Directive, HostListener, ElementRef} from '@angular/core';
- @Directive({
- selector: '[myPhoneMask]',
- })
- export class PhoneMaskDirective {
- ddd: string = '';
- prefix: string = '';
- end: string = '';
- mobileDigit: string = '';
- formattedPhone: string = '';
- elementValue: string;
- lastKnowLength: any = 0;
- constructor(_elRef: ElementRef) {}
- setDDD(inputLength) {
- if (inputLength >= 2) {
- this.ddd = this.elementValue.slice(0, 2);
- return '(' + this.ddd + ') ';
- }
- return '';
- }
- setPrefix(inputLength) {
- if (inputLength >= 6) {
- this.prefix = this.elementValue.slice(2, 6);
- return this.prefix;
- }
- return '';
- }
- setEnd(inputLength) {
- if (inputLength === 10) {
- this.end = this.elementValue.slice(6, 10);
- this.formattedPhone += '-' + this.end;
- this.formatPush(this.formattedPhone);
- }
- return;
- }
- setEndMobile(inputLength) {
- if (inputLength === 11) {
- this.mobileDigit = this.elementValue.slice(6, 7);
- this.formattedPhone += this.mobileDigit + '-';
- this.end = this.elementValue.slice(7, 11);
- this.formattedPhone += this.end;
- this.formatPush(this.formattedPhone);
- }
- return;
- }
- @HostListener('keyup') onInputChange() {
- // Receive the input value (Digits only)
- this.elementValue = this.getModelValue();
- // store the length to compare and allow the user to backspace
- let inputLength: any = this.elementValue.length;
- // set the DDD code
- this.formattedPhone = this.setDDD(inputLength);
- // set the Prefix number
- this.formattedPhone += this.setPrefix(inputLength);
- /*
- * inputLength 10 and 11 do the formatPush on them selves to display the effect
- * of the number changing the position between the slash -
- */
- this.setEnd(inputLength);
- // if it's mobile, in brazil it has 11 digits including DDD
- this.setEndMobile(inputLength);
- // If the user want to backspace, it'll compare if the lastKnowLength is bigger then the inputLength
- if (this.lastKnowLength < inputLength) {
- // this will format the field while user is typing
- if (inputLength === 2 || inputLength === 6) {
- this.formatPush(this.formattedPhone);
- }
- }
- // set the lastKnowLength
- this.lastKnowLength = inputLength;
- }
- formatPush(formattedValue) {
- this._elRef.nativeElement.value = formattedValue;
- }
- getModelValue() {
- let elementValue = this._elRef.nativeElement.value;
- if (/[a-z]/.test(elementValue)) {
- this.formatPush(elementValue.replace(/\D/g, ''));
- }
- return elementValue.replace(/\D/g, '');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement