Inherit imports from parent module to child module in Angular2

Lion picture Lion · Feb 12, 2017 · Viewed 13.8k times · Source

I made an Angular2 app like described here. It has two components (A,B) which are imported by the global app.module. My idea was, to include shared modules in app.module, so I don't need to mess up every module with redundant code. I want to do that for example with the FormsModule. So in the app.module I have

imports: [
    UniversalModule,
    CommonModule,
    FormsModule,
    AModule
    RouterModule.forRoot([])
],

exports: [FormsModule]

But in the A module I got the exception Can't bind to 'ngModel' since it isn't a known property of 'select'. which seems caused by the missing FormsModule. It only works, when I import the FormsModulein every child module too using imports: [FormsModule]. That's exactly what I want to avoid.

According to this question, I tried to import the AppModule in the child module A. This doesn't work and give me the exception Exception: Call to Node module failed with error: Error: Unexpected value 'undefined' imported by the module 'AModule'

How can I inherit the imports to child modules? I need this for pipes, too.

Answer

Günter Zöchbauer picture Günter Zöchbauer · Feb 12, 2017

Just create a feature module (or shared module) that exports the components, directives, and pipes, that are usually used together and import this module to modules where you want to use any of these.

There is no way to make components, directives, or pipes available globally. They need to be added to imports of every module where they are used. All you can do is combine modules and make them available by importing only a single or few modules.