I've searched here and there, and I am not able to find something specific about formatting a phone number.
Currently, I am retrieving phone numbers form a JSON in the following format:
25565115
However, I want to achieve this result:
02-55-65-115
For that, I believe that I need to use a custom pipe and I don't think that there is a built-in one that does it automatically.
Can you please give me some guidance on how to do so?
To format phone numbers in the US, Canada, and other NANP (North American Numbering Plan) countries, enclose the area code in parentheses followed by a nonbreaking space, and then hyphenate the three-digit exchange code with the four-digit number.
Angular Pipes Multiple custom pipesIt is possible to bundle all frequently used pipes in one Module and import that new module in any component needs the pipes.
Steps Involved In Creating a Custom Pipe In Angular are: 1) Create a Pipe Class and decorate it with the decorator @Pipe. 2) Supply a name property to be used as template code name. 3) Register your Pipe in the module under declarations. 4) Finally, implement PipeTransform and write transformation logic.
StackBlitz
pipe
implementation in TS would look like this
import { Pipe } from "@angular/core"; @Pipe({ name: "phone" }) export class PhonePipe { transform(rawNum) { rawNum = rawNum.charAt(0) != 0 ? "0" + rawNum : "" + rawNum; let newStr = ""; let i = 0; for (; i < Math.floor(rawNum.length / 2) - 1; i++) { newStr = newStr + rawNum.substr(i * 2, 2) + "-"; } return newStr + rawNum.substr(i * 2); } }
Declare the PhonePipe in your NgModule's declarations
import {Component} from 'angular/core'; @Component({ selector: "my-app", template: ` Your Phone Number: <input [(ngModel)]="myNumber" /> <p> Formatted Phone Number: <b>{{ myNumber | phone }}</b> </p> ` }) export class AppComponent { myNumber = "25565115"; }
There are many things that can be improved, I just made it work for this particular case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With