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?
In this scenario, create another shared module in that import all the component which is being used in multiple module. In shared component. declare those component. And then import shared module in appmodule as well as in other module where you want to access.
@NgModule takes a metadata object that describes how to compile a component's template and how to create an injector at runtime. It identifies the module's own components, directives, and pipes, making some of them public, through the exports property, so that external components can use them.
A feature module is an organizational best practice, as opposed to a concept of the core Angular API. A feature module delivers a cohesive set of functionality focused on a specific application need such as a user workflow, routing, or forms.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With