How to consume Custom pipe defined in a angular library?

44 views Asked by At

I am facing issue while importing a custom pipe from angular library to main app.It is a custom library and I am using static forroot approach to load the library's module.I have declared and exported the pipe in library and also have imported custom library in the main app module.But unfortunately, a try to use the pipe is failing with error 'customPipe' could not be found in the 'AppComponent'. Here is project structure:

  • src
    • app
      • app.module.ts
      • app.component.ts
  • library
    • src

      • lib
        • pipes

          custom.pipe.ts

        • customlib.module.ts

      public-api.ts

Sharing the code here:

customPipe.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'customPipe'
})
export class customPipe implements PipeTransform {
  constructor(){}
  transform(value1: string,value2:string): unknown {
    return value1+value2
  };
}

customlib.module.ts

import { HTTP_INTERCEPTORS, HttpClient, HttpClientModule } from '@angular/common/http';
import { Router } from '@angular/router';
import { customPipe } from 'path to customPipe'
@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
  ],
  declarations: [
    customPipe
  ]
  ,exports: [customPipe]
})

export class customLibraryModule {
  constructor (@Optional() @SkipSelf() module: customLibraryModule) {
    if (module) {
      throw new Error(
        'custom is already loaded.Import it in the AppModule only.');
    }
  }

  static forRoot(): ModuleWithProviders<customLibraryModule> {
    return {
      ngModule: customLibraryModule,
      providers: [
       {provide:'service',useValue:customService},// not of any use here for my usecase
      ]
    };
  }

public-api.ts

export { customPipe } from 'path to CustomPipe';
export * from './lib';

app.module.ts

@NgModule({
    declarations: [
    ],
    imports: [
        customLibraryModule.forRoot()
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
    {{'test' | customPipe:'value1' : 'value2'}}
  </div>

app.component is not able to find customPipe and throws "customPipe could not be found in the 'app.component'".

Please help to fix the issue .Thanks in advance!

1

There are 1 answers

0
Naren Murali On

Try importing the library directly in the imports array, that will load the exports of the module, forRoot will load the providers I think!

@NgModule({
    declarations: [
    ],
    imports: [
        customLibraryModule,    // <-- changed here!
        customLibraryModule.forRoot()
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }