简体   繁体   中英

How to dynamically add components to NgModule in Angular 4 and @angular/cli?

Is there a way to add components to the declarations and entryComponents attribute dynamically (Angular 4, angular/cli 1.1.2)?

Background: I created an AppInfo.ts where developers can define additional components that will be loaded dynamically using ComponentFactoryResolver (something like widgets). This AppInfo.ts consists of an static array of components (AppInfo.components) .

How can I push elements of this array to the NgModule Decorator?

I got this solution that does work using ng serve but not using ng build --prod:

export const ngmodule = {
  declarations: [...],
  entryComponents:[ ],
  imports: [...],
  bootstrap: [
    AppComponent
  ],
  providers: [...]
};

for (let i = 0; i < AppInfo.components.length; i++) {
  const comp = <any> AppInfo.components[i];
  ngmodule.entryComponents.push(comp);
  ngmodule.declarations.push(comp);
}

@NgModule(ngmodule)

If I try to build my app using ng build --prod I get this error:

ERROR in Cannot determine the module for class DynCompExample in /Users/x/Documents/x/src/app/x/x/DynCompExample.component.ts! Add DynCompExample to the NgModule to fix it.

But if I use ng serve It works fine.

What I do is export an array of components and use that in @NgModule

You can split this between internal components, and developer components.

Internal.components.ts

export const INTERNAL_COMPONENTS = [
       FooterComponent,
       HeaderComponent,
       SideBarComponent
];

Developer.components.ts

export const DEVELOPER_COMPONENTS = [
       WidgetComponent,
       CustomerComponent,
       NewFeatureComponent
];

Then you import those into your module file and use them.

import {INTERNAL_COMPONENTS} from './Internal.components.ts';
import {DEVELOPER_COMPONENTS} from './Developer.components.ts';

@NgModule({
    declarations: [
        INTERNAL_COMPONENTS,
        DEVELOPER_COMPONENTS
    ],
    exports: [
        INTERNAL_COMPONENTS,
        DEVELOPER_COMPONENTS
    ]
})
export class AppModule {

}

Leave the entry component as a single main component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM