Tuesday, October 18, 2016

Angular2 Custom Pipe for Phone


Angular2 pipes are great for formatting data labels.  And Angular2 already comes with a bunch of built-in pipes out-of-the-box, including the Date Pipe, Decimal Pipe, Currency Pipe, LowerCase and UpperCase Pipes, JSON Pipe, Percent Pipe, Slice Pipe, and Async Pipe.

“Why isn’t there a Pipe for telephone numbers?” you might ask.  Standardizing on phone number formats is notoriously tricky because, with all the different international phone number conventions, there are no standards.  So, if you need a Pipe for phone numbers, you need to build a custom Pipe yourself.  Unfortunately I could not find one on the web, so I wrote one myself.


You will need to import “Pipe” from Angular2 Core, give your new pipe a name, and implement or override the “Transform” function.


As you can see in the code, this Pipe will transform the input by a) stripping out any non-numeric characters, b) take only the first 10 valid characters, and c) apply the area code parenthesis and the hyphen separator.

To consume our Phone Pipe in our component, we would need to a) import the Pipe and b) declare it in the pipes array inside our Component decorator.


In our view, we apply the Phone Pipe as simply as below:


Regardless of the user’s input (entering invalid characters or entering more than 10 characters), the Phone Pipe will format it as you desired.

This Phone Pipe works great when you are just formatting a label.  But what if you wish to format the data in an input control?  Then we are talking about applying pipes to a control with two-way data binding, and that would be much trickier.

In this article, I showed you how to implement a custom Phone Pipe.  In my next blog, I will discuss how you can apply formatting and validation using pipes on an input control.

4 comments:

  1. Unfortunately, the example trims off the last digit. It should return splice(0, 14) since there are 2 paranthesis, 7 numbers, 1 slash, and a single space after the second paran. That's 14 characters. Thanks for the example

    ReplyDelete
  2. I agree with Anthony. The splice should be 14:
    return ("(" + area + ") " + number).trim().slice(0, 14);

    ReplyDelete