Load NgModule entryComponents dynamically using se

2020-06-03 04: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 "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 {}

This actually works, but only if I have compiled and the server is running first.

If, I try to recompile and run it, I get this constant error:

"Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function,"

My other thought was, is there a way to put the loading of the components in the "export class testModule {}" portion to fill the array and then pass it to NgModule?

From my current test it doesn't work, but I am still new to this so I might be missing something.

Hope someone can help. Thanks!

Here is the code that creates the compile error:

I just did ng new test-app.

Then in the test-app folder i did npm install.

I created /src/app/services/components-loader.service.ts.

import { Injectable } from '@angular/core';
import { ViewContainerRef, ViewChild, ComponentFactoryResolver } from '@angular/core';

@Injectable()
export class ComponentLoaderService {
    constructor(private componentFactoryResolver: ComponentFactoryResolver){}

    static getComponents(components: any[]): any[] {
        var tmp = Array();

        for (var i = 0; i < components.length; ++i){
            if (components[i].key == 0){
                tmp.push(components[i].component);
            }
        }

        return tmp;
    }

    load(container: ViewContainerRef, components: any[]): void {
        // clear 
        container.clear();

        for (var i = 0; i < components.length; ++i){
            if (components[i].key == 0 || components[i].key == 'site'){
                const childComponent = this.componentFactoryResolver.resolveComponentFactory( components[i].component );

                // at this point we want the "child" component to be rendered into the app.component:
                container.createComponent(childComponent);          
            }            
        }
    }
}

I created a file /src/app/components.ts.

import { TestComponent } from './test.component';

export const mainComponents = [
    { key: 0, component: TestComponent },        
];

I created a file /src/app/test.component.ts.

import { Component } from '@angular/core';

@Component({
  template: `test`,
})
export class TestComponent {}

I modified /src/app/app.module.ts to look like this.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { mainComponents } from './components';
import { ComponentLoaderService } from './services/components-loader.service';

let componentsToLoad = ComponentLoaderService.getComponents(mainComponents);

@NgModule({
  declarations: [
    AppComponent,
    componentsToLoad
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [ componentsToLoad ],
})
export class AppModule { }

When I compile using ng serve, i get this error:

10% building modules 2/2 modules 0 activeError: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol AppModule in D:/angularjs/test-app/src/app/app.module.ts, resolving symbol AppModule in D:/angularjs/test-app/src/app/app.module.ts

回答1:

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