Search code examples
angularangular-directiveangular-module

why it is necessary to import CommonModule to other custom/child modules when it is being imported and re-exported in the root module (AppModulle)


Assume I have an app that has two modules

  • AppModule
  • MyChildModule

CommonModule is imported and re-exported by AppModule

MyChildModule is imported to AppModule

app.module.ts

@NgModule({
    declarations: [
      AppComponent,
    ],
    imports: [
        BrowserModule,
        CommonModule,
        MyChildModule
    ],
    exports:[
        CommonModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})

CommonModule is NOT IMPORTED to MyChildModule

childModule.module.ts

@NgModule({
    declarations: [
      MyChildComponent,
    ],
    imports: [
    ],
    exports:[
        MyChildComponent,
    ]
})

my-child-module-component.ts

export class ChildModuleComponent{
      showMessage:boolean;
      constructor(){
         this.showMessage = true;
      }
}

Child-module-component.html

<h1 *ngIf ='showMessage'> Hello World </h1>

now the issue is when I add childComponent to appComponent it says *ngIf is not a know property. since *ngIf is a directive of commonModule and both childModule and commonModule are imported to the same module which is AppModule

app.component.ts

<my-child-component></my-child-component> <!-- *it should display *Hello World text* -->

Solution

  • There is no need to export it in AppModule

    1. Nothing is "importing App Module" in your example, and in general.
    2. You can always import that module elsewhere, so no need to export here.

    You need to import CommonModule inside your ChildModule, From the doc https://angular.io/api/common/CommonModule , you need it for *ngIf pipe for example.

    Think of the childModule as an independent container, where to start it has to have everything needed ( in this case, it's ask for *ngIf, ie. CommonModule )

    IMPORTANT: Once declared in a module, a component can't be imported inside another module

    What you want to do in your example :

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

    Let me know if that helps.