angularangular-datatablesangular2-custom-pipes

use angular 4 Pipe in 2 component


I have component base angular4 app and in every component i'm using DataTable Plugin and custom DataFilterPipe, when i import like below in every component the error i get is ERROR Error: Uncaught (in promise): Error: Type DataFilterPipe is part of the declarations of 2 modules. Please consider moving DataFilterPipe to a higher module. then i created a new module called dataFilterModule

import:

import {DataTableModule} from "angular2-datatable";
import {DataFilterPipe} from "../plugins/datatable/datafilterpipe";
import {HttpModule} from "@angular/http";
import {FormsModule} from "@angular/forms";

dataFilterModule:

import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {DataTableModule} from "angular2-datatable";
import {DataFilterPipe} from "../plugins/datatable/datafilterpipe";
import {HttpModule} from "@angular/http";
import {FormsModule} from "@angular/forms";

@NgModule({
    imports: [
        CommonModule,
        DataTableModule,
        FormsModule,
        HttpModule
    ],
    declarations: [
        DataFilterPipe
    ],
    exports: [
        DataFilterPipe
    ]
})
export class dataFilterModule {}

then import this module in my AppModule but!! the error i get is:

The pipe 'dataFilter' could not be found

I added exported dataFilterModule like below but there is no any good news!

export class dataFilterModule {
   static forRoot() {
     return {
         ngModule: DataFilterPipe,
         providers: [],
     };
   }
}

Edit: My custom filter:

import * as _ from 'lodash';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'dataFilter'
})
export class DataFilterPipe implements PipeTransform {

    transform(array: any[], query: string): any {
        if (query) {
        return _.filter(array, row=>row.name.indexOf(query) > -1);
     }
    return array;
  }
 }

Solution

  • The answer is a Shared Module. Check out this similar post I answered a few days ago.