Search code examples
angularangular-componentsangular-pipeangular-module

Pipes within components from shared module


I have been building myself an application in NG and run across a problem using a pipe in a component, from a shared module.

Shared Module (cut all the other stuff out):

import { NgModule } from '@angular/core';
import { FilterByPipe, OrderByPipe } from './pipes/index';


@NgModule({
    imports: [],
    declarations: [FilterByPipe],

    exports: [
        //Pipes
        FilterByPipe,
    ],

    providers: [FilterByPipe]

})
export class SharedModule { }

My question, how can I use the exported pipe FilterByPipe from within another components code? i.e.

export class ViewSomethingComponent implements OnInit {
    constructor(private _filterBy: FilterByPipe)

    filterSomething(data){ this._filterBy.transform(data,{a:'value'})}
}

I have tried importing the pipe directly, but that gives me dependency issues as its not provided from the parent module. Besides adding the pip to the parent module, and then using it as a provider for dependency injection, is there no other way to use a pipe exported by a shared component?


Solution

  • Import SharedModule to your root AppModule.

    Then you can easily use your FilterByPipe in any component within AppModule.

    import { FilterByPipe } from '@angular/common';
    class FilterByPipe {
      constructor(private fillterPipe: FilterByPipe) {}
      transformData(data) {
        this.fillterPipe.transform(data);
      }
    }
    

    And add following, or you will get an error

    providers: [FilterByPipe]