WBM
WBM

Reputation: 43

Angular 11.0.4 Can't find pipe

I'm trying to use a pipe to highlight certain text based on a dropdown selection in the app, I have the pipe module declared in app module, and registered as a provider for the component I want to use it in but I get an error saying can't find pipe with name. Below is the relevant code and how I'm trying to use it. Am I declaring the pipe incorrectly or registering incorrectly?

highlight-text.pipe.ts taken from 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]
})

How I'm trying to use it in page.component.html:

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

The error I am getting:

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

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

Upvotes: 4

Views: 1894

Answers (1)

bvdb
bvdb

Reputation: 24710

A Pipe actually isn't really a provider. If you define it on a module, you have to put it in the declarations: [...] section.

Having said that, a component doesn't have a declaration section.

So, that means, you cannot declare a pipe on a component. You can however declare it on a module, which will make it available to all components in that module. (See discussion: https://github.com/angular/angular/issues/29763 )

(However, if you do want to limit the scope to one component, then you could of course create a module for that specific component.)

Upvotes: 3

Related Questions