StephenRios StephenRios - 1 month ago 9
Javascript Question

Using Sub-Modules that implement their own components

So right now I am importing a whole bunch of individual components in

app.module
to cover all the things I need to use.

AppModule
-Header Component
-Header Sub-Component 1
-Header Sub-Component 2
-Header Sub-Component 3


What I would ideally like to do is rather than import them all in the
app.module
, I would like to create a
header.module
that handles importing all of its own components so that the
app.module
only needs to import the
header.module
and the
header.module
handles its own dependencies.

I've tried so many ways of doing this, but I just can't seem to get it to work. What does the structure need to be?

I was trying to just do:

import { HeaderModule } from "./header/header.module";


In
AppModule
, and then have a
HeaderModule
that looked like:

// Core
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

// Components
import { HeaderComponent } from "./header.component";
import { ButlerBarComponent } from './butler/butler.component';

@NgModule({
declarations: [
HeaderComponent,
ButlerBarComponent
],
imports: [BrowserModule],
providers: [],
bootstrap: [ButlerBarComponent]
})

export class HeaderModule { }


Just to try to get the module > component relationship set up, but when I do this the declaration that calls the header component in
app.component.html
no longer has access to the
header
selector.

What do I need to do to make this work so I can put the
<header></header>
tag in
app.component.html
and have the application load
header.module
and the subsequent
header.component
and make the
header
selector available to
app.component.html
?

Answer

You need to declare all those components in your HeaderModule and then export them so AppModule can access them when you import HeaderModule in AppModule. Also, you should import BrowserModule only in AppModule, in your other modules you should import CommonModule instead because it contains common directives such as ngIf, ngFor, ngClass etc. Finally, you don't need bootstrap here because you only bootstrap one component in your app and you do it in AppModule. So, your HeaderModule should look like this:

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

import { HeaderComponent } from "./header.component";
import { ButlerBarComponent } from './butler/butler.component';

@NgModule({
    imports: [
        CommonModule
    ],
    declarations: [
        HeaderComponent,
        ButlerBarComponent
    ],
    exports: [
        HeaderComponent,
        ButlerBarComponent
    ]
})

export class HeaderModule { }

Now you only need to add HeaderModule to your AppModule's imports and you should be ready to go.