Angular 自定义管道为什么没有生效?
我在 Angular 项目里写了个自定义管道,用来格式化手机号,但模板里用了却没反应,数据还是原样显示。
已经加到 declarations 里了,也确认模块导入没问题。比如我这样用:{{ user.phone | phoneFormat }},但页面上还是显示原始的 “13812345678”。
管道代码大概是这样的:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'phoneFormat' })
export class PhoneFormatPipe implements PipeTransform {
transform(value: string): string {
if (!value) return '';
return value.replace(/(d{3})(d{4})(d{4})/, '$1-$2-$3');
}
}
是不是哪里漏了?纯数字字符串应该能匹配上才对啊……
把管道代码里的正则表达式改成这样:
另外建议加个空格分隔符看起来更清晰:
通用的做法是调试时可以先 console.log 一下传入的 value 和返回值,确保数据格式符合预期。我之前也在这上面栽过跟头,写完正则不测试直接上,结果发现错得离谱。
对了,别忘了加上 null 检查,有时候数据可能会是 undefined:
这样应该就能正常工作了,记得测试几个不同格式的手机号看看效果。