parth
parth

Reputation: 674

Angular 2- Change text display format as per pattern

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">

Upvotes: 2

Views: 1836

Answers (1)

user4676340
user4676340

Reputation:

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;
  }
}

Upvotes: 4

Related Questions