Load NgModule entryComponents dynamically using service

前端 未结 1 986
借酒劲吻你
借酒劲吻你 2021-02-08 12:23

Hi I am new to angular2 and typescript. I am loading components dynamically and I was wondering if there is a way to declare my components using a service in the module\'s \"dec

相关标签:
1条回答
  • 2021-02-08 12:46
    @NgModule({
        declarations: [],
        exports: []
    })
    export class testModule {
        static withComponents(components: any[]) {
            return {
                ngModule: testModule,
                providers: [
                    {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: components, multi: true}
                ]
            }
        }
    }
    

    Other module:

    import { ComponentLoaderService } from './../../services/component-loader.service';
    
    let componentsToLoad = ComponentLoaderService.getComponents();
    
    @NgModule({
        imports: [
            BrowserModule,
            FormsModule,
            testModule.withComponents([
                ...componentsToLoad
            ])
        ],
        declarations: [
            AppComponent,
            ...componentsToLoad
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule {
    }
    

    By making use of ANALYZE_FOR_ENTRY_COMPONENTS here, you are able to add multiple components to the NgModule.entryComponents entry dynamically.

    0 讨论(0)
提交回复
热议问题