我正在尝试创建一个自定义管道,它将一个字符替换为另一个字符(用例:用空格分隔的单词替换连字符的单词),但在遵循在线指南和 Angular 文档后,我似乎无法让它工作。
<强> stackblitz
pipe.ts
@Pipe({
name: 'replace'
})
export class ReplacePipe implements PipeTransform {
transform(value: string, replace: string, withThis: string): any {
return value.replace(replace, withThis);
}
}
html 使用
<!-- hyphenate = 'some-hyphenated-string' -->
<div>{{hyphenated | replace: {replace: '-', withThis: ' '} }}</div>
最佳答案
1) 您没有正确调用自定义管道:
而不是:
<div>{{hyphenated | replace: {replace: '-', withThis: ' '} }}</div>
用途:
<div>{{hyphenated | replace: '-': ' '}}</div>
<小时/>
2) 您的replace
用法仅替换字符串中的第一个匹配项:
而不是:
return value.replace(replace, withThis);
用途:
return value.replace(new RegExp(replace, 'g'), withThis);
关于javascript - Angular - 自定义管道不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52079577/