Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: pipes - How to format a phone number?

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?

like image 831
Hamza L. Avatar asked Apr 27 '16 16:04

Hamza L.


People also ask

How do you format a phone number?

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.

Can I use two pipes in Angular?

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.

How can you create custom pipe in Angular?

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.


1 Answers

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


Usage:

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.

like image 193
Ankit Singh Avatar answered Sep 24 '22 09:09

Ankit Singh