Ham*_* L. 18 pipes-filters angular
我在这里和那里搜索过,我无法找到关于格式化电话号码的具体信息.
目前,我正在使用以下格式从JSON中检索电话号码:
25565115
但是,我想实现这个结果:
02-55-65-115
为此,我认为我需要使用自定义管道,我不认为有一个自动执行它的内置管道.
你能告诉我一些如何做的指导吗?
Ank*_*ngh 18
pipeTS中的实现看起来像这样
import {Pipe} from 'angular2/core';
@Pipe({
name: 'phone'
})
export class PhonePipe{
transform(val, args) {
val = val.charAt(0) != 0 ? '0' + val : '' + val;
let newStr = '';
for(i=0; i < (Math.floor(val.length/2) - 1); i++){
newStr = newStr+ val.substr(i*2, 2) + '-';
}
return newStr+ val.substr(i*2);
}
}
Run Code Online (Sandbox Code Playgroud)
import {Component} from 'angular2/core';
@Component({
selector: 'demo-app',
template: '<p>{{myNumber | phone }}</p>',
pipes: [PhonePipe]
})
export class App {
constructor() {
this.myNumber= '25565115';
}
}
Run Code Online (Sandbox Code Playgroud)
有许多事情可以改进,我只是让它适用于这个特殊情况.
Rob*_*hoe 14
在"user5975786"的基础上,这里是与Angular2相同的代码
import { Injectable, Pipe } from '@angular/core';
@Pipe({
name: 'phone'
})
export class PhonePipe
{
transform(tel, args)
{
var value = tel.toString().trim().replace(/^\+/, '');
if (value.match(/[^0-9]/)) {
return tel;
}
var country, city, number;
switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);
break;
case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);
break;
case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);
break;
default:
return tel;
}
if (country == 1) {
country = "";
}
number = number.slice(0, 3) + '-' + number.slice(3);
return (country + " (" + city + ") " + number).trim();
}
}
Run Code Online (Sandbox Code Playgroud)
gio*_*pds 13
我刚刚在这篇文章中碰到了自己,展示了如何使用名为libphonenumber的谷歌库来做到这一点。似乎他们在许多不同的语言中使用这个库并且有非常广泛的支持(链接只是到 JS 包版本)。以下是我将其应用于葡萄牙语/巴西电话号码的方法:
第一的:
npm i libphonenumber-js
Run Code Online (Sandbox Code Playgroud)
然后:
# if you're using Ionic
ionic generate pipe Phone
# if you're just using Angular
ng generate pipe Phone
Run Code Online (Sandbox Code Playgroud)
最后:
import { Pipe, PipeTransform } from '@angular/core';
import { parsePhoneNumber } from 'libphonenumber-js';
@Pipe({
name: 'phone'
})
export class PhonePipe implements PipeTransform {
transform(phoneValue: number | string): string {
const stringPhone = phoneValue + '';
const phoneNumber = parsePhoneNumber(stringPhone, 'BR');
const formatted = phoneNumber.formatNational();
return formatted;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用此库实现许多不同的方式。上面有很多很多方便的方法,你可以去阅读看看它是否适合你。
竖起大拇指,如果你喜欢。=]
从JSON数据服务格式化电话号码时,这是我能想到的最简单的解决方案.
<p>0{{contact.phone.home | slice:0:1}}-{{contact.phone.home | slice:1:3}}-{{contact.phone.home | slice:3:5}}-{{contact.phone.home | slice:5:8}}</p>
Run Code Online (Sandbox Code Playgroud)
这会将"25565115"格式化为"02-55-65-115"
希望这有助于某人!
| 归档时间: |
|
| 查看次数: |
33379 次 |
| 最近记录: |