Make component, directive and pipe public and use outside a module

939 views Asked by At

How do I make a component, directive and pipe public? This is because when I add them to declarations array in a module, they become visible everywhere in the module where they are declared and are private to the module. If I've to use outside the module what should be done.

2

There are 2 answers

2
micronyks On BEST ANSWER

You can use a shared Module which is responsible for sharing common components, pipes and directives.
please note its just a naming convention to use sharedModule or coreModule, but you can use any other module name eg xyzModule. Import thing is that make sure common things are declared within export array

import { NgModule }            from '@angular/core';
import { CommonModule }        from '@angular/common';

import { CustomComponent}  from 'path';
import { CustomPipe}       from 'path';
import { CustomDirective}  from 'path';

@NgModule({
  imports:      [ CommonModule ],
  declarations: [ CustomComponent, CustomPipe, CustomDirective],
  exports:      [ CustomComponent, CustomPipe, CustomDirective]
})
export class SharedModule { }

Use it in App/Root Module or any other feature or lazy loaded feature module like this,

AppModule Or let's say ClientModule

import {SharedModule } from 'path'

@NgModule({

   imports: [..., sharedModule]

})
0
diopside On

just need to make sure the relevant items are in your module's export line

 exports:      [ CustomComponent, CustomPipe, CustomDirective]

Then any other module that implements that module will have access to those things