angular-pipe 两分钟上手自定义管道过滤器

环境&需求

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';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值