我对ng2和inputmask有些问题。例如,我有这个代码 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工作正常。但我的[(ngModel)]
没有用。有谁知道如何解决我的问题?
答案 0 :(得分:1)
我已解决此问题。
http://plnkr.co/edit/tN6y5d2fsl0b7cRq6Prv?p=preview
您需要使用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);
}
}
在HTML代码中我使用
<input [tdInputmask]="'+7(999)999-99-99'" (tdInputmaskUnmaskedValue)="val3 = $event">