我正在尝试编写代码输入掩码以格式化电话号码,例如(123)456-7890。我快完成了
我创建了指令来执行格式,但我被粘贴操作卡住了。
如果用户在文本框中输入电话号码,则可以正常工作。
但是,如果用户将10位电话号码复制并粘贴到文本框中,则格式化仅发生在文本框中,而不会反映在模型绑定中。
文本框显示->(123)456-7890,但在ngModel绑定中为1234567890
StackBlitz中的实际代码
https://stackblitz.com/edit/angular-648zrp
代码
html模板
<form #myForm="ngForm">
<div>
<span>Copy and paste the below text in textbox </span>
<br>
<br>
<span>1234567890</span>
</div>
<hr>
<br>
<div>
<input name="phoneNumber" id="phoneNumber" class="form-control" phone autocomplete="off"
maxlength="14" (blur)="onSubmit()" [(ngModel)]="phoneNumber"/>
<br/>
<br/>
<span>PhoneNumber NgModel Bind : {{phoneNumber}}</span>
<br/>
<br/>
<span *ngIf="myForm?.controls?.phoneNumber">PhoneNumber form value : {{myForm.controls.phoneNumber.value}}</span>
</div>
</form>
Component
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
phoneNumber: string;
}
Directive
import { Directive } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[ngModel][phone]',
host: {
'(ngModelChange)': 'onInputChange($event)'
}
})
export class MaskDirective {
constructor(public model: NgControl) {}
onInputChange(value) {
var x = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
this.model.valueAccessor.writeValue(value);
}
}
请尝试@HostListener
@HostListener('paste',['$event']) onEvent($event) {}