1

I am making a Reactive Form in Angular 2, which allows the user to enter a phone number

        <div class="col-md-4 top-space-small">
            <div class="input-label" style="margin-bottom:0">Home phone:</div>
            <input type="text" 
                   formControlName="homePhone"
                   class="pf-input form-control"  />
        </div>

Is there a way to mask the user input in a phone format so they are typing in digits but as they do the displayed input value looks like (xxx) xxx-xxxx

tt9
  • 5,784
  • 6
  • 42
  • 65
  • Possible duplicate of [Input mask fields in Angular2 forms](http://stackoverflow.com/questions/37800841/input-mask-fields-in-angular2-forms) – silentsod Nov 11 '16 at 18:40
  • @silentsod he is asking about reactive forms. The other example is using ngModel – Nix Mar 30 '17 at 19:10

1 Answers1

0

I share how to resolve this detail using a mask

1.- In your view you must place your text box with an identifier as shown

<input type="text" id="phone" placeholder="(55)-5555-5555">

2.- In your component, add AfterViewInit so that when the main view finishes loading, start loading the secondary view which will have the script to perform the function of the telephone format as shown below.

import { Component, AfterViewInit } from '@angular/core';
@Component({
selector:'my-app',
template: '<input type="text" id="phone" placeholder="(55)-5555-5555"})
export class AppComponent implements AfterViewInit
{
   ngAfterViewInit()
   {
     document.getElementById('phone').addEventListener('input',    function (e) 
     {
      var x = e.target.value.replace(/\D/g, '').match(/(\d{0,2})(\d{0,4})(\d{0,4})/);
      e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
     });
   }
}

Ok, explain code:

NgAfterView load of the script. With document.getElementById('phone') select the id phone

AddEventListener allow the moment convert in real time to phone format

If you required change 555-5555-55, you may change the section .match(/\d{0,2}) to the numbers to want

Regards

  • This one worked great for me. The only thing is, I had to take one extra step, after running into this in Angular: Property 'value' does not exist on type 'EventTarget'.ts(2339) I found help for my solution here: https://stackoverflow.com/questions/42066421/property-value-does-not-exist-on-type-eventtarget and wrote something like: var target = e.target as HTMLInputElement; and then used target where e.target was priorly and it worked great. – Sean Halls Jun 04 '20 at 03:32