angularpipes-filters

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?


Solution

  • 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.