Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Injectable, Directive, ElementRef, Output, EventEmitter} from '@angular/core';
- import {NgModel} from '@angular/common';
- import {FormControl} from "@angular/forms";
- declare var jQuery: any;
- @Directive({
- selector: '[mask]',
- providers: [
- NgModel
- ],
- host: {
- '(input)': 'onInputChange($event)'
- }
- })
- @Injectable()
- export class INPUT_MASK_DIRECTIVE {
- public mask: any = ['(', /[0-9]/, /[0-9]/, /[0-9]/, ')', '-', /[0-9]/, /[0-9]/, /[0-9]/, '-', /[0-9]/, /[0-9]/, /[0-9]/, /[0-9]/];
- /**
- *
- * @type {number}
- */
- public lastPosition: number = 0;
- /**
- *
- * @type {string}
- */
- public currentValue: string = '';
- /**
- *
- * @type {string}
- */
- public previousValue: string = '';
- /**
- *
- * @type {any}
- */
- public el: any;
- /**
- *
- * @type {FormControl}
- */
- public formControl = new FormControl();
- /**
- *
- * @param _elementRef
- * @param _model
- */
- public constructor(private _elementRef: ElementRef,
- private _model: NgModel) {
- }
- /**
- *
- * @param {any} event
- */
- onInputChange(event: any) {
- let value: any = event.target.value.split('');
- let position: number = event.target.selectionStart;
- let result: any = [];
- let empty: boolean = true;
- for (let i = 0; i < this.mask.length; ++i) {
- if (typeof this.mask[i] == 'object') {
- if (value[i] && this.mask[i].test(value[i])) {
- result.push(value[i]);
- empty = false;
- } else {
- result.push(' ');
- }
- } else {
- result.push(this.mask[i]);
- }
- }
- if (position == 0 && empty) {
- result = [];
- }
- position = this.getPosition(position);
- this.lastPosition = position;
- value = result.join('');
- this._model.viewToModelUpdate(value);
- this._model.control.updateValue(value);
- this._model.valueAccessor.writeValue(value);
- event.target.setSelectionRange(position, position);
- }
- /**
- *
- * @param {number} position
- * @param {boolean} del
- * @return {number}
- */
- public getPosition(position: number, del = false): number {
- if (this.mask[position] && typeof this.mask[position] != 'object') {
- if (position > this.lastPosition) {
- ++position;
- } else {
- del = true;
- --position;
- }
- return this.getPosition(position, del);
- } else {
- if (del) {
- ++position;
- }
- return position;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement