How do you load a dynamic module by variable in Angular 9?

喜你入骨 提交于 2020-06-26 07:38:50

问题


I have the following code to load a module dynamically:

export class DynamicQuestionComponent {
    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private viewContainerRef: ViewContainerRef
    ) {}

    @Input() form: FormBase;
    @Input() formgroup: FormGroup;
    @ViewChild('content', { read: ViewContainerRef, static: true }) content: ViewContainerRef;

    @Input() set question(qvalue){
        if (qvalue){
            this.content.clear();
            var compath = `./${qvalue.qType}-question.component`;
            var testpath = './proto-question.component';
            import('./proto-question.component').then( dyncomp => {
                const component = this.viewContainerRef.createComponent(this.componentFactoryResolver.resolveComponentFactory(dyncomp.ProtoQuestionComponent));
                (<any>component).instance.form = this.form;
                (<any>component).instance.question = qvalue;
                (<any>component).instance.formgroup = this.formgroup;
                this.content.insert(component.hostView);
                component.injector.get(ChangeDetectorRef).markForCheck();
            })
        }
    }
}

Currently, this is the only way it works, if I hard code the component path inside of the import function. I want to be able to pass a variable into the import function, but each time I switch to the variable, I get the dreaded cannot find module error:

ERROR Error: Uncaught (in promise): Error: Cannot find module './proto-question.component'

As you can see, I even tested a variable that is exactly the same as the hardcoded version and that fails as well.

I feel like there must be a setting to make this work properly.

I"m using:

Angular 9.1.9

Angular CLI 9.1.4

Assuming I can get past the dynamic variable issue, then I need to figure out how to get pass in the dynamic component into the resolveComponentFactory call.


回答1:


Unfortunately loading a dynamic module by variable is not possible. I have similar issue and i can't find a solution. Dynamically import modules with dynamic routes



来源:https://stackoverflow.com/questions/62304831/how-do-you-load-a-dynamic-module-by-variable-in-angular-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!