环境&需求
angular2+
需求
自定义一个给手机号打星号的管道过滤器。
代码
1.pipe
1.指令创建pipe
ng g pipe pipes/format-phone
import { Pipe, PipeTransform } from '@angular/core';
// 手机号打星号
// 例子: 17605998382 => 176xxxx8382
@Pipe({
name: 'formatPhone'
})
export class FormatPhonePipe implements PipeTransform {
transform(value: string, ...args: unknown[]): any {
console.log('value: ', value);
if(value && value.length == 11) {
let tel = "" + value;
let reg=/(\d{3})\d{4}(\d{4})/;
let newTel = tel.replace(reg, "$1****$2")
return newTel;
}else{
return value;
}
}
}
2.app.module
注意:如果不是用指令创建的需要再app.module中引入,直接是全局管道,无需在组件中引入。
import { FormatPhonePipe } from './pipes/format-phone.pipe';
@NgModule({
declarations: [FormatPhonePipe]
//...
3.组件中使用
<div>{{ phoneNum | formatPhone }}</div>
// ts
public phoneNum: any = '17605889393';