Skip to content
Advertisement

How to create a directive in Angular to mask us phone number without changing model?

I have a directive in Angular Js that masks phone numbers to US format (xxx) xxx-xxxx ,

JavaScript
JavaScript

How can I recreate the same directive in Angular ( typescript ) ?

I created a directive from another post but It alters the model too, My Requirement is that it should visually show as (xxx) xxx-xxxx, but the model value should not be changed i.e. it should be xxxxxxxxxx

My Stackblitz demo -> https://stackblitz.com/edit/angular6-phone-mask-7tglv9?file=app%2Fapp.component.html

Advertisement

Answer

Good comments under the question. If the end result is the need to mask the phone number, being able to change the number but still keep the unmasked number in the control, then I would recommend using a package for this. Complex template operations on input and form is no easy feat. https://www.npmjs.com/package/ngx-mask

Trick here is to use X with custom pattern. Idea from: https://github.com/JsDaddy/ngx-mask/issues/547#issuecomment-548596982

Html:

JavaScript

TS:

JavaScript

enter image description here

Working example: https://stackblitz.com/edit/ngx-mask-xrpqce?file=src%2Fapp%2Fapp.component.html

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement