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

前端 未结 5 1667
灰色年华
灰色年华 2020-12-14 17:18

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

5条回答
  •  没有蜡笔的小新
    2020-12-14 17:40

    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: 
        

    Formatted Phone Number: {{ myNumber | phone }}

    ` }) export class AppComponent { myNumber = "25565115"; }

    There are many things that can be improved, I just made it work for this particular case.

提交回复
热议问题