【问题标题】:Angular 11.0.4 Can't find pipeAngular 11.0.4 找不到管道
【发布时间】:2021-05-28 06:16:09
【问题描述】:

我正在尝试使用管道根据应用程序中的下拉选择突出显示某些文本,我在应用程序模块中声明了管道模块,并注册为我想要使用它的组件的提供程序,但我得到一个错误,说找不到带有名称的管道。以下是相关代码以及我如何尝试使用它。我是声明管道不正确还是注册不正确?

highlight-text.pipe.ts取自https://stackoverflow.com/a/44962110/11881461

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'highlightText'
})

export class HighlightTextPipe implements PipeTransform {

    transform(value: any, args: any): any {
        if (!args) {return value;}
        var re = new RegExp(args, 'gi'); //'gi' for case insensitive and can use 'g' if you want the search to be case sensitive.
        return value.replace(re, "<mark>$&</mark>");
    }
}

app.module.ts

@NgModule({
  declarations: [
    {other declarations},
    HighlightTextPipe
  ],

page.component.ts

import {HighlightTextPipe} from '../../pipes/highlight-text.pipe';

@Component({
  {other declarations}
  providers: [HighlightTextPipe]
})

我如何尝试在 page.component.html 中使用它:

<span>{{ text | highlightText : 'Annex'}}</span>

我得到的错误:

Error: src/app/components/page.component.html:89:69 - error NG8004: No pipe found with name 'highlightText'.

89           <span>{{text | highlightText : 'Annex'}}</span>

【问题讨论】:

    标签: angular


    【解决方案1】:

    管道实际上并不是真正的提供者。如果你在一个模块上定义它,你必须把它放在declarations: [...] 部分。

    话虽如此,组件没有declaration 部分。

    也就是说,您不能在组件上声明管道。但是,您可以在模块上声明它,这将使该模块中的所有组件都可以使用它。 (见讨论:https://github.com/angular/angular/issues/29763

    (但是,如果您确实想将范围限制为一个组件,那么您当然可以为该特定组件创建一个模块。)

    【讨论】:

    • 这为我解决了,谢谢!对于任何有类似问题的人,为所有应该有管道工作的组件使用共享模块(对我来说,需要它的组件实际上并不是应用程序模块的一部分,因为我发现)
    猜你喜欢
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2019-01-06
    • 2017-03-25
    • 2020-09-21
    • 2021-05-22
    • 1970-01-01
    相关资源
    最近更新 更多