angular – 在ngFor中动态添加组件
我有一个“仪表板”,可以加载配置的元素.
仪表板模板具有: <div class="dash-container" [ngGrid]="gridConfig"> <div *ngFor="let box of boxes; let i = index" [(ngGridItem)]="box.config" (onItemChange)="updateItem(i,$event)" (onResize)="onResize(i,$event)" (onDrag)="onDrag(i,$event)" (onDragStop)="onDragStop(i,$event)" [ngClass]="box.class" > <div class="handle"><h4>{{box.title}}</h4></div> <div [innerHTML]= "box.content"></div> </div> </div> 现在< div [innerHTML] =“box.content”>< / div>不起作用,因为非标准元素被消毒. 我看一下我能找到的动态组件的例子 – 但我所看到的只是他们只是将组件添加到当前组件 – 但我需要它们在一个非常特定的div中,如上例所示. ComponentFactoryResolver通常与@ViewChild一起使用. ngAfterViewInit() { const dashWidgetsConf = this.widgetConfigs(); for (var i = 0; i < dashWidgetsConf.length; i++) { const conf = dashWidgetsConf[i]; @ViewChild(conf.id,{read: ViewContainerRef}) var widgetTarget: ViewContainerRef; var widgetComponent = this.componentFactoryResolver.resolveComponentFactory(UnitsComponent); widgetTarget.createComponent(widgetComponent); } } @viewchild给’装饰者在这里无效’.
经过一番研究,这是我提出的解决方案(工作在角4.0.0).
按ID加载所有ViewContainerRef目标: @ViewChildren('dynamic',{read: ViewContainerRef}) public widgetTargets: QueryList<ViewContainerRef>; 然后遍历它们以获取目标,为组件创建工厂并调用createComponent. ngAfterViewInit() { const dashWidgetsConf = this.widgetConfigs(); const widgetComponents = this.widgetComponents(); for (let i = 0; i < this.widgetTargets.toArray().length; i++) { let conf = dashWidgetsConf[i]; let component = widgetComponents[conf.id]; if(component) { let target = this.widgetTargets.toArray()[i]; let widgetComponent = this.componentFactoryResolver.resolveComponentFactory(component); let cmpRef: any = target.createComponent(widgetComponent); if (cmpRef.instance.hasOwnProperty('title')) { cmpRef.instance.title = conf.title; } } } } widgetComponents是一个对象{key:component},widgetConfigs是我存储特定组件信息的地方 – 比如标题,组件ID等. 然后在模板中: <div *ngFor="let box of boxes; let i = index" > <ng-template #dynamic></ng-template> </div> 目标的顺序与我的conf中的顺序相同(框是从它生成的) – 这就是为什么我可以按顺序循环它们并使用i作为索引来获得正确的conf和组件. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- twitter-bootstrap-3 – 遵循Bootstrap 3的手册说明,获取ym
- Scala中的Trait,FunctionN或trait-inheriting-FunctionN?
- 角度指令隔离范围的可选双向约束
- Bootstrap导航栏各元素操作方法(表单、按钮、文本)
- scala – Spark数据帧写入方法编写许多小文件
- unix – 如何在新窗口中在vim中打开一个新文件
- Bootstrap Modal 如何清除已定义的事件
- 利用AXIS开发Webservice(一) —— 如何发布自己的webservic
- WebServices 简介
- 调用webservice异常java.lang.ClassCastException: java.la