Angular2, inputmask ngModel binding

Issue

I have some problem with ng2 and inputmask. For example I have had this code
component.html

<div class="form-group col-sm-7"> 
  <label class="control-label" for="sender-phone">Phone *</label>  
  <input type="text" [(ngModel)]="sender.phone" class="form-control" id="sender-phone" placeholder="Phone">
</div>

component.ts

ngAfterViewInit() {  
  let phoneNumberInput = document.getElementById('sender-phone'); 
  let inputmask = new Inputmask('+7(999)999-99-99');  
  inputmask.mask(element);  
}

Inputmask is working good. But my [(ngModel)] didn’t work. Anyone know how I can resolve my issue ?

My code for example http://plnkr.co/edit/F3pob7hH2ZrJv0MDNa9x?p=preview

Solution

I have resolve problem of this issue.

http://plnkr.co/edit/tN6y5d2fsl0b7cRq6Prv?p=preview

You need create directive with InputMask

@Directive({ selector: '[tdInputmask]' })
export class InputmaskDirective {
@Output('tdInputmaskUnmaskedValue') unmaskedValueEmitter = new EventEmitter();

@Input() set defaultValue (value: string) {
    //this._defaultColor = colorName || this._defaultColor;
}

@Input('tdInputmask') mask: string;

private el: HTMLElement;
constructor(el: ElementRef) {
    this.el = el.nativeElement;
}

ngAfterViewInit() {
   let inputmask = new Inputmask(this.mask);
    let elementCallback = () =>  {
        if (this.el.inputmask) {
            this.unmaskedValueEmitter.emit('7' + this.el.inputmask.unmaskedvalue());
            //if (!this.el.inputmask.isComplete()) {
            //    this.el.parentElement.classList.add('has-error');
            //} else {
            //    this.el.parentElement.classList.remove('has-error');
            //}
        }
    };

    inputmask.opts.oncomplete = elementCallback;
    inputmask.opts.onincomplete = elementCallback;
    inputmask.opts.onBeforePaste = (pastedValue: string) => {
        if (pastedValue[0] == '7' || pastedValue[0] == '8') {
            return pastedValue.slice(1);
        }
        return pastedValue;
    };
    inputmask.mask(this.el);
}
}

And in HTML code I use

<input [tdInputmask]="'+7(999)999-99-99'" (tdInputmaskUnmaskedValue)="val3 = $event">

Answered By – FRAGnat

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.