kumara
kumara

Reputation: 937

how to use angular pipe as a shared component or shared module

I am using below function as a pipe, for get unique values to the drop down. i need to use this in multiple components. how i create reusable component to use this function.

 @Pipe({
  name: 'unique',
  pure: false
})

export class UniquePipe implements PipeTransform {
  transform(value: any): any {
      if (value !== undefined && value !== null) {
          return _.uniqBy(value, 'orgName');
      }
      return value;
  }
}

Upvotes: 1

Views: 4963

Answers (2)

ashish.gd
ashish.gd

Reputation: 1768

Simply create a module named as SharedModule and then export the pipe from it. That way it will be available as the public API for any of the modules that import SharedModule.

Example:

import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { UniquePipe} from './pipes/unique.pipe';




@NgModule({
  declarations: [
    UniquePipe,
  ],
  imports: [
    CommonModule,
    HttpClientModule,
  ],
  exports: [
    UniquePipe,
  ]
})
export class SharedModule {}

You can read more about this at:

  1. https://angular.io/guide/sharing-ngmodules#sharing-modules
  2. Style Guide: https://angular.io/guide/styleguide#shared-feature-module

Upvotes: 7

Amrit
Amrit

Reputation: 2165

In your shared.module.ts file you just need to add it in declarations and exports and then you can import this module in any other module where you want to use this pipe.

in pipe.components.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'mypipe',
})
export class MyPipe implements PipeTransform {
  // convert dictionary to list so that it can be iterated in html
  transform(objects: any = []) {
    return Object.values(objects);
  }
}

then in your shared.module.ts :

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ValueArrayPipe } from '../pipe/pipe.component';


@NgModule({
    imports: [
        CommonModule
    ],
    declarations: [ValueArrayPipe ],
exports: [ValueArrayPipe ],
})
export class SharedPipesModule { }

Upvotes: 3

Related Questions