2

I want to change display format of text field input for Mobile number. Ex.

For number 1212121212, it should display (121) 212-1212 inside text and just for view purpose only. I also want full text on insert it into the DB. How can i achieve this in Angular 2 text input?

<p>How it is now</p>
<input type="text" value="1212121212" name="mobile"><br>
<p>How it should look</p>
<input type="text" value="(121) 212-1212" name="mobile2">
parth
  • 624
  • 1
  • 10
  • 29

1 Answers1

4

You can do something like this with a pipe (just add a number at the end of the input).

I'm of course using a very simple regex, but you can create the one you want.

transform(value: string, args?: any): any {
  const regex: RegExp = new RegExp(/(\d{3})(\d{3})(\d{4})/);
  const match = value.match(regex);
  if(match) {
    return `(${match[1]})${match[2]}-${match[3]}`;
  } else {
    return value;
  }
}
  • That's perfect. Just one question. Is it possible to start patterning from the first latter instead of 10 letters? Here after inserting 10 digits it is changing it's view. – parth Mar 22 '18 at 10:26
  • Yes, that's what I told you, for that you will need a monstruous regex (or several little regexes). –  Mar 22 '18 at 10:26
  • as a piece of advice, if you use several little regexes, start with the biggest one, and finish with the simplest one. Otherwise, you might be surprised by the results you get. –  Mar 22 '18 at 10:29