How to load component dynamically using component name in angular2?

后端 未结 5 1945
鱼传尺愫
鱼传尺愫 2020-11-29 03:58

I am currently loading angular components dynamically in my application using following code.

export class WizardTabCo         


        
5条回答
  •  -上瘾入骨i
    2020-11-29 04:31

    It's also possible to access through import:

    someComponentLocation.ts - contains enum of possible components:

    export * from './someComponent1.component'
    export * from './someComponent2.component'
    export * from './someComponent3.component';
    

    importer component:

    import * as possibleComponents from './someComponentLocation'
    ...
    
    @ViewChild('dynamicInsert', { read: ViewContainerRef }) dynamicInsert: ViewContainerRef;
    
    constructor(private resolver: ComponentFactoryResolver){}
    

    then you can create instance of component for example:

    let inputComponent = possibleComponents[componentStringName];
    if (inputComponent) {
        let inputs = {model: model};
        let inputProviders = Object.keys(inputs).map((inputName) => { return { provide: inputName, useValue: inputs[inputName] }; });
        let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
        let injector: ReflectiveInjector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicInsert.parentInjector);
        let factory = this.resolver.resolveComponentFactory(inputComponent as any);
        let component = factory.create(injector);
        this.dynamicInsert.insert(component.hostView);
    }
    

    note that component has to be in @NgModule entryComponents

提交回复
热议问题