指定索引处的动态组件放置不正确

时间:2018-07-23 10:24:08

标签: angular typescript angular-directive

我试图在Angular中显示一个简单的项目列表,并在侧面显示可点击的div;根据用户选择,该组件应在被点击的组件下方动态创建一个新组件。

为此,我正在使用ComponentFactoryResolver,没有任何相关问题;但是,使用ViewContainerRef作为父对象,即使我在createComponent()方法中将其指定为参数,也找不到如何将创建的组件放置在指定的索引处。

app.component.html

<h3>Click on the arrow to create a component below the item clicked.</h3>

<div #myContainer>
  <div *ngFor="let thing of things; let index = index">
    <div class="inline click" (click)="thingSelected(thing, index)"> > </div>
    <div class="inline">{{thing.id}}</div>
    <div class="inline">{{thing.name}}</div>
    <div class="inline">{{thing.value}}</div>
  </div>
</div>

app.component.ts

export class AppComponent  {  
  @ViewChild('myContainer', { read: ViewContainerRef }) container: ViewContainerRef;

  things = [];
  constructor(private componentFactoryResolver: ComponentFactoryResolver){
    for(let i=0; i < 10; i++)
      this.things.push({id: i, name: "thing" + i, value: 5 * i});    
  }

  thingSelected(thing: any, index: number){
    let component = this.container.createComponent(this.componentFactoryResolver.resolveComponentFactory(DetailComponent), index);
    component.instance.id = thing.id;    
  }
}

我还创建了一个stackblitz示例来说明问题:我缺少什么或做错了什么?

要澄清:

  1. 我想在PrimeNg库的TurboTable中复制类似于"RowExpand" functionality的内容。 用户单击一行,并在单击的位置创建一个动态组件
  2. 我不知道运行时组件的类型:这就是为什么我要动态创建组件的原因(所以,在html模板中指定它不是我所需要的

1 个答案:

答案 0 :(得分:3)

好的,这是@ViewChildren

的工作示例

https://stackblitz.com/edit/angular-gxmj4s?file=src%2Fapp%2Fapp.component.ts

  @ViewChildren('details', { read: ViewContainerRef }) containers: QueryList<ViewContainerRef>;

  thingSelected(thing: any, index: number) {
    const containersArray = this.containers.toArray();
    let component = containersArray[index].createComponent(this.componentFactoryResolver.resolveComponentFactory(DetailComponent));
    component.instance.id = thing.id;
  }

<div #myContainer>
  <div *ngFor="let thing of things; let index = index">
    <div class="inline click" (click)="thingSelected(thing, index)"> > </div>
    <div class="inline">{{thing.id}}</div>
    <div class="inline">{{thing.name}}</div>
    <div class="inline">{{thing.value}}</div>
    <div #details></div>
  </div>
</div>

结果

enter image description here