角度2:管道-如何格式化电话号码? [英] Angular 2: pipes - How to format a phone number?

查看:83
本文介绍了角度2:管道-如何格式化电话号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里和那里搜索过,但找不到关于格式化电话号码的具体信息.

I've searched here and there, and I am not able to find something specific about formatting a phone number.

当前,我正在以以下格式从JSON检索电话号码:

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

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?

推荐答案

StackBlitz

pipe实施看起来像这样

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);
  }
}


在NgModule的声明中声明PhonePipe


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.

这篇关于角度2:管道-如何格式化电话号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆