Angular 2 can't find a component declared in my feature module

Jim Jenkins picture Jim Jenkins · Sep 13, 2016 · Viewed 12k times · Source

I'm having a tough time getting modules to work in Angular 2. I have created a plunk that demonstrates the problem. In the plunk, you'll see I have app.module. This module imports app-common.module, which contains a component to display page headers. The template for the top level component, app.component contains the selector for this component. Here's app.common.module:

@NgModule({
imports:[CommonModule, FormsModule],
declarations: [PageHeaderComponent]
})
export class AppCommonModule { }

Here's app.module:

@NgModule({
imports:      [AppCommonModule, BrowserModule],
declarations: [AppComponent ],
bootstrap:    [ AppComponent ]
})
export class AppModule { }

When the application is run, it throws an error that "ref-pageheader" is not a known element. If I declare the component in app.module, it works fine. So, why can't I declare this component in a module that gets imported into the main app.module? It seems Angular can't find it when this is done. What am I doing wrong? Am I missing something?

Answer

yurzui picture yurzui · Sep 13, 2016

I guess you should export it like:

@NgModule({
    imports:[CommonModule, FormsModule],
    declarations: [PageHeaderComponent],
    exports: [PageHeaderComponent]
})
export class AppCommonModule { } 

This way other components could use the component.

Otherwise PageHeaderComponent will only be available inside of AppCommonModule

See also

We export the ContactComponent so other modules that import the ContactModule can include it in their component templates.

All other declared contact classes are private by default

Export declarable classes that components in other modules should be able to reference in their templates. These are your public classes. If you don't export a class, it stays private, visible only to other component declared in this module.