如何在Angular 9中通过变量加载动态模块? [英] How do you load a dynamic module by variable in Angular 9?
问题描述
我有以下代码可以动态加载模块:
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();
})
}
}
}
当前,如果我在import函数中对组件路径进行硬编码,则这是唯一的方法.我希望能够将一个变量传递给导入函数,但是每次我切换到该变量时,都会得到可怕的找不到模块错误:
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.
我正在使用:
Angular 9.1.9
Angular 9.1.9
Angular CLI 9.1.4
Angular CLI 9.1.4
假设我可以解决动态变量问题,那么我需要弄清楚如何将动态组件传递到resolveComponentFactory调用中.
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.
推荐答案
不幸的是,无法通过变量加载动态模块.我有类似的问题,我找不到解决方案. 动态导入具有动态路由的模块
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
这篇关于如何在Angular 9中通过变量加载动态模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!