在模板引用的特定位置创建动态组件

时间:2019-02-12 06:19:30

标签: angular

有没有一种方法来获取特定的模板引用,然后基于click事件创建组件。

我想要的是,当单击按钮时,应基于单击按钮的模板引用folderContainer的位置创建动态组件。

我当前的问题是,组件总是在模板引用的第一个生成的div中创建。

app.component.ts

import {
  Component, ViewContainerRef,
  ViewChild,
  ComponentFactoryResolver
} from '@angular/core';

import { FolderComponent } from './folder/folder.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  folders = ['folder1', 'folder2', 'folder3'];

  @ViewChild('folderContainer', { read: ViewContainerRef }) folderContainer: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) { }

  createFolder(event) {
    console.log(event)
    const folderFactory = this.resolver.resolveComponentFactory(FolderComponent);
    const folder = this.folderContainer.createComponent(folderFactory);
    console.log(folder)
  }

}

app.component.html

<div *ngFor="let folder of folders">
  <p>{{folder}}</p>
  <button (click)="createFolder($event)">ADD</button>
  <div #folderContainer>
  </div>
</div>

这里是stackblitz link.

1 个答案:

答案 0 :(得分:2)

您可以使用ViewChildren而不是ViewChild进行此操作。使用ViewChildren,您将循环获得所有templates的引用数组。

@ViewChildren('folderContainer', { read: ViewContainerRef }) foldersContainer: QueryList<ViewContainerRef>;

  constructor(private resolver: ComponentFactoryResolver) { }

  createFolder(event, index) {
    const containers = this.foldersContainer.toArray()
    const folderFactory = this.resolver.resolveComponentFactory(FolderComponent);
    const folder = containers[index].createComponent(folderFactory);
  }

html

<div *ngFor="let folder of folders; let i=index">
  <p>{{folder}}</p>
  <button (click)="createFolder($event, i)">ADD</button>
  <div #folderContainer>
  </div>
</div>

选中此demo