代码之家  ›  专栏  ›  技术社区  ›  davecar21

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

  •  1
  • davecar21  · 技术社区  · 7 年前

    是否有方法获取特定的模板引用,然后根据Click事件创建组件。

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

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

    应用组件.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(应用程序组件.html)

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

    这里是 stackblitz link.

    1 回复  |  直到 7 年前
        1
  •  2
  •   Amit Chigadani    7 年前

    你可以用 ViewChildren 而不是 ViewChild . 使用 观察儿童 您将获得所有 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

    推荐文章