【问题标题】:Create Dynamic Component in specific location of template reference在模板引用的特定位置创建动态组件
【发布时间】:2019-07-05 17:39:24
【问题描述】:

有没有办法获取特定的模板引用,然后根据点击事件创建组件。

我想要的是,当单击按钮时,应根据单击按钮的模板引用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.

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用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

    【讨论】:

    • 我看到使用 ViewChild 我们将无法获取模板数组,而是会查找模板的第一个元素?
    • 是的,这就是发生的事情,因为所有元素都有相同的引用。 ViewChildren 是解决方案
    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2018-11-14
    相关资源
    最近更新 更多