Search code examples
angulartypescriptpipeionic4

The pipe 'safe' could not be found ionic 4


I am using a pipe to sanitize trusted resourceurls in an ionic 4 app

safe.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {}

  transform(url: string) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }

}

app.module.ts

import { SafePipe } from './services/safe.pipe';<---------

@NgModule({
  declarations: [AppComponent, SafePipe],<----------
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule, 
    HttpClientModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    SafePipe <----------
    { ...

my.page.html

... [data]="urlData | safe" ...

Console error... Error:The pipe 'safe' could not be found!

I followed a tutorial on this and added SafePipe to providers after googling, what is it that am I missing here?? Thanks


Solution

  • A pipe doesn't have to be added to the providers. Just make sure you use the SafePipe in a component that is declared in the same module or the component's module should import a module where the SafePipe is declared and exported.

    I can see you declared the SafePipe in AppModule and used it inside MyPageComponent.

    You need to make a SharedModule and declare and export the SafePipe in this ShareModule. You import this SharedModule in a module where you want to use this pipe.

    Add more components or pipes that can be used across the application.

    Here is a stackblitz demo for showing how to use the SharedModule:

    https://stackblitz.com/edit/shared-pipe