题目描述我想用Angular的ComponentFactoryResolver动态创建一个Component然后追加到body里面,下面是我的实现步骤//modal.component.jsimport{Component,ViewChild,ViewContainerRef}from'@angular/core';@Component({selector:'modal',template:`modalworks!`,})exportclassModalComponent{constructor(options:ModalOptions){console.log(options);}}exportclassModalOptions{title:string;content:string;}//modal.service.js//...import@Injectable({providedIn:'root',})exportclassModalService{//...constructorpubliccreate(options:ModalOptions){letcomponentFactory=this.resolver.resolveComponentFactory(ModalComponent);letinjector=Injector.create([{provide:ModalOptions,useValue:options,},]);letcomponentRef=componentFactory.create(injector);letcomponentRootNode=(componentRef.hostViewasEmbeddedViewRef).rootNodes[0]asHTMLElement;this.container.appendChild(componentRootNode);returncomponentRef;}}上面的代码在运行的时候会报错,错误信息如下ERRORError:Uncaught(inpromise):Error:Can'tresolveallparametersforModalComponent:(?).Error:Can'tresolveallparametersforModalComponent:(?).请问是我注入参数的方式不对么?应该怎么对动态创建的Component的构造函数注入参数么?谢谢!
2 回答

梵蒂冈之花
TA贡献1900条经验 获得超5个赞
ModalComponent构造参数中要写修饰符如public、private、readonly等等。这样才会自动构造属性并创建。constructor(publicoptions:ModalOptions){console.log(options);}
添加回答
举报
0/150
提交
取消