I am trying to write code input mask to format the phone number like (123) 456-7890. I almost done.
I created directive to perform the format, but I'm stuck on the paste operation.
If the user type the phone number in textbox its working fine.
But if the user copy and paste the 10 digit phone number in textbox the formatting happened only in textbox not reflecting in model binding.
textbox show -> (123) 456-7890 but in ngModel bind is 1234567890
Actual code in StackBlitz
https://stackblitz.com/edit/angular-648zrp
Code
html template
<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);
}
}
Please try @HostListener
@HostListener('paste',['$event']) onEvent($event) {}
Reference:- http://embed.plnkr.co/hsisILvtKErBBOXECt8t/
here's the code I wrote recently. It not only validates the phone pattern but automatically adds parenthesis and dashes as you enter numbers
public isValidFlg:boolean = true;
validatePhoneNo(field) {
var phoneNumDigits = field.value.replace(/\D/g, '');
this.isValidFlg = (phoneNumDigits.length==0 || phoneNumDigits.length == 10);
var formattedNumber = phoneNumDigits;
if (phoneNumDigits.length >= 6)
formattedNumber = '(' + phoneNumDigits.substring(0, 3) + ') ' + phoneNumDigits.substring(3, 6) + '-' + phoneNumDigits.substring(6);
else if (phoneNumDigits.length >= 3)
formattedNumber = '(' + phoneNumDigits.substring(0, 3) + ') ' + phoneNumDigits.substring(3);
field.value = formattedNumber;
}
and the input:
<input type="text" (input)="validatePhoneNo($event.target)" placeholder="(___) ___-____">
<div *ngIf="!isValidFlg">Invalid Format"</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.