1

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?

Doug
  • 547
  • 10
  • 23

1 Answers1

2

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] 
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
  • While I can use the pipe inside HTML ('{{somedata | filterby: 'value'}}') when trying to inject it into the controller it returns an error that no class can be found. – Doug Nov 13 '17 at 22:34
  • I have updated the answer. for more clear view see this : https://stackoverflow.com/questions/35144821/angular-2-4-use-pipes-in-services-and-components – Sangwin Gawande Nov 14 '17 at 04:02