1

Inside of my SharedModule I want to split up related pieces of code into multiple child modules. When I do that however, I lose the common imports from the shared module. For example, I import the FormsModule before my SharedChildModule, but when I try to use ngModel inside my SharedChildModule it tells me that ngModel isn't available. Is it possible to have child modules inside the shared module and also to have those modules inherit the modules from the SharedModule?

When I include the components and directives from ChildSharedModule directly in the SharedModule I have no issues. It is only when I attempt to move those into a child module and then import the whole module into SharedModule that I get the errors.

@NgModule({
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,

    ChildSharedModule
  ],
  imports: [
    CommonModule,
    FormsModule,

    ChildSharedModule
  ]
})
export class SharedModule { }

@NgModule({
  declarations: [
    ChildValidatorDirective,
    ChildControlComponent
  ],
  exports: [
    ChildValidatorDirective,
    ChildControlComponent
  ]
})
export class SharedChildModule {}

1 Answer 1

2

You can not push down dependencies of modules, but you can export modules upwards.

@NgModule({
    declarations: [],
    exports: [
        ChildSharedModule
    ],
    imports: [
        ChildSharedModule
    ]
})
export class SharedModule { }

@NgModule({
    imports: [
        CommonModule,
        FormsModule
    ],
    declarations: [
        ChildValidatorDirective,
        ChildControlComponent
    ],
    exports: [
        ChildValidatorDirective,
        ChildControlComponent,
        CommonModule,
        FormsModule
    ]
})
export class SharedChildModule {}

Now SharedModule will import SharedChildModule and will receive everything that is exported by that child module. Since SharedModule is also exporting SharedChildModule then parents who import it will also receive CommonModule and FormsModule.

You are basically breaking tree shaking here, and making unit testing very difficult.

Angular will no longer be able to drop unused modules, because you are coupling everything together. It will also become difficult to remove FormsModule from SharedChildModule because you won't know how many parents depend upon it.

You should try to keep your modules as singular and flat as possible, and have each module import only what it specifically needs.

You can export another module when the consumer doesn't know that other module is a requirement.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.