Load NgModule entryComponents dynamically using service

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 "declarations" and "entryComponents".

Using typescript, I am able to achieve it by doing the following:

import { ComponentLoaderService } from './../../services/component-loader.service';

let componentsToLoad = ComponentLoaderService.getComponents();

@NgModule({
  declarations: [ componentsToLoad ],
  entryComponents: [ componentsToLoad ],
})
export class testModule {}

@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.

链接地址: http://www.djcxy.com/p/94264.html

上一篇: 用变量键从表中找到val

下一篇: 动态使用服务加载NgModule entryComponents