简体   繁体   English

角度-自定义管道不起作用?

[英]Angular - Custom pipe not working?

I am attempting to create a custom pipe that will replace one character with another (use case: replacing hyphenated words with space separated words), but I cannot seem to get it working after following online guides and the Angular docs. 我试图创建一个自定义管道,将一个字符替换为另一个字符(用例:用空格分隔的单词替换带连字符的单词),但是在遵循在线指南和Angular文档之后,似乎无法使它正常工作。

stackblitz stackblitz

pipe.ts pipe.ts

@Pipe({
  name: 'replace'
})
export class ReplacePipe implements PipeTransform {

  transform(value: string, replace: string, withThis: string): any {
    return value.replace(replace, withThis);
  }

}

html usage html用法

<!-- hyphenate = 'some-hyphenated-string' -->

<div>{{hyphenated | replace: {replace: '-', withThis: ' '} }}</div>

1) You're not calling your custom pipe correctly: 1)您没有正确调用自定义管道:

Instead of: 代替:

<div>{{hyphenated | replace: {replace: '-', withThis: ' '} }}</div>

Use: 采用:

<div>{{hyphenated | replace: '-': ' '}}</div>

2) Your replace usage only replaces the first occurrence in the string: 2)您的replace用法仅替换字符串中的第一个匹配项:

Instead of: 代替:

return value.replace(replace, withThis);

Use: 采用:

return value.replace(new RegExp(replace, 'g'), withThis);

Updated stackblitz 更新了stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM