0

I have a component that I would like to reuse in a few places throughout my applications. As such, I created a module within my core module with new component. The error I'm getting is 'foo' is not a known element.

You can see a demo here. You will see the component I wish to share module in app/core/foo/foo.component.ts, which has been imported into CoreModule. And you will see FooComponent (using selector foo) being used in app/crisis/crisis-list.component.ts.

I've read the Angular 2 module documentation to death and can't put my finger on why I can't use FooComponent wherever I please.

What am I missing?

onetwothree
  • 612
  • 9
  • 19

3 Answers3

1

You should import FooModule in CrisisModule like that;

import { FooModule } from '../core/foo/foo.component';
...
@NgModule({
     imports: [CommonModule, CrisisRoutingModule, FooModule],
     ...
})
export class CrisisModule{}

Whenever you want to use any component, just import the module which includes declaration of component.

ulubeyn
  • 2,214
  • 1
  • 16
  • 25
1

You have to choice :

1- Import your module in the module that is going to use it

2- Declare the component (not the module ) in the module that your going to use it.

BUT :

Module approach is better , because if you have a module inside another module , you cannot declare your component in both of them , but you can import the module in both of them :!

Milad
  • 22,895
  • 9
  • 62
  • 76
  • I remember thinking this but thought the point of `CoreModule` was that everything in there was freely accessible to the entire application. – onetwothree Dec 02 '16 at 16:35
  • That would only work if you import CoreModule in every single Module :) – Milad Dec 03 '16 at 02:25
1

To make common component working in various module, you have to export that Component from particular module by specifying exports option of NgModule like below, so that will be act as shareable Component

exports: [CommonComponent] //it will contain the list of shareable Components

and then inject that module inside the another module wherever you want to use Common Component.

NOTE: Even you had mentioned CommonComponent to be there inside declartions option of module, it will not allow to use those Components , Pipe's, Directive's in other module directly, to make it work you have to export specific component which should work as shareable.

Pankaj Parkar
  • 127,691
  • 20
  • 213
  • 279
  • Ah, I see. I thought that simply exporting it from `FooModule`, then importing and exporting that module in `CoreModule` that it would be made available to the entire application. – onetwothree Dec 02 '16 at 16:34