为了账号安全,请及时绑定邮箱和手机立即绑定

Angular的ComponentFactory创建Component的时候怎么对Component的构造函数注入参数呢?

Angular的ComponentFactory创建Component的时候怎么对Component的构造函数注入参数呢?

至尊宝的传说 2019-05-13 08:36:37
题目描述我想用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);
}
                            
查看完整回答
反对 回复 2019-05-13
  • 2 回答
  • 0 关注
  • 1548 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号