在ngFor中动态添加组件

Ago*_*ony 17 angular

我有一个"仪表板",可以加载已配置的元素.仪表板模板具有以下内容:

  <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>
Run Code Online (Sandbox Code Playgroud)

现在<div [innerHTML]= "box.content"></div>不行,因为非标准元素被消毒了.运行最新的Angular 2.4.6(RC 6).

我看一下我能找到的动态组件的例子 - 但我看到的只是他们只是将组件添加到当前组件 - 但我需要它们在一个非常特定的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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

@viewchild给'装饰者在这里无效'.如何从conf列表中加载组件(在循环中)并将它们添加到组件中的特定div(divs got #{{conf.id}})中?

Ago*_*ony 26

经过一些研究,这是我提出的解决方案(工作在角4.0.0).

ViewContainerRef按ID 加载所有目标:

@ViewChildren('dynamic', {read: ViewContainerRef}) public widgetTargets: QueryList<ViewContainerRef>;
Run Code Online (Sandbox Code Playgroud)

然后循环遍历它们以获取目标,为组件创建工厂并调用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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

widgetComponents是一个对象{key: component},widgetConfigs是我存储特定组件信息的地方 - 如标题,组件ID等.

然后在模板中:

<div *ngFor="let box of boxes; let i = index" >
    <ng-template #dynamic></ng-template>
</div>
Run Code Online (Sandbox Code Playgroud)

目标的顺序与我的conf(boxes由它生成)相同 - 这就是为什么我可以按顺序循环它们并使用i作为索引来获得正确的conf和组件.

  • @Agony如果未来"盒子"的价值发生变化怎么办?例如.新框将添加到现有框中.我可以看到,在动态加载组件的情况下,DOM不会使用新框进行更新. (3认同)

dje*_*lin 6

如果你有这样的模式:

<div *ngFor="for item in items">
  <!-- needs to be one per item -->
  <ng-template details-directive></ng-template>
</div>
Run Code Online (Sandbox Code Playgroud)

我建议将该指令包装在一个组件中:

@Component({
  selector: 'details-wrapper',
  template: '<ng-template details-directive></ng-template>'
})
export class DetailsWrapper {
  @Input item?: Item;
  // Dynamically load details using the regular solution.
}
Run Code Online (Sandbox Code Playgroud)

并将其作为 for 循环:

<div *ngFor="for item in items">
  <details-wrapper [item]="item"></details-wrapper>
</div>
Run Code Online (Sandbox Code Playgroud)