【问题标题】:How to dynamically create component inside child component in Angular?如何在Angular中的子组件内动态创建组件?
【发布时间】:2020-08-07 12:56:36
【问题描述】:

我正在尝试实现类似 mat-table 的轻量版形式的 Angular Material。而且我无法在子组件内创建组件。这是最后的一些代码和指向 stackblitz 的链接。

在一些*.html文件中:

<table uiTable></table>

基本 UiTable 组件:

// ui-table.component.ts

@Component({
  selector: 'table[uiTable]',
  template: `
    <thead uiTableHead></thead>
  `,
})
export class UiTableComponent implements AfterContentInit {

  @ViewChild(UiTableHeadDirective, {static: true}) 
  private tableHead: UiTableHeadDirective;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
  ) {}

  public ngAfterContentInit() {
    const rowFactory = this.componentFactoryResolver.resolveComponentFactory(UiTableRowComponent);

    this.tableHead.viewContainer.clear();
    this.tableHead.viewContainer.createComponent(rowFactory);
  }

}

ui-table-head.directiveui-table-row.component - 只是空的角度指令和注入 ViewContainerRef 的组件。

我希望在ngAfterContentInit 完成后我会得到类似的东西

<table uiTable>
    <thead uiTableHead>
        <tr uiTableRow></tr>
    </thead>
</table>

但我得到的不是它

<table uiTable>
    <thead uiTableHead></thead>
    <tr uiTableRow></tr>
    <!--container-->
    <!--container-->
</table>

为什么?我从tableHead.viewContainer 调用createComponent 方法,但是在uiTable 内部创建了新组件。 怎么了?

Stackblitz 链接 - https://stackblitz.com/edit/ui-table

【问题讨论】:

  • 历史上决定将动态创建的组件放置在锚点旁边。在你的情况下锚是thead
  • @yurzui 哦,好的(有什么方法可以在anchor 中创建组件吗?将anchor 放在thead 中,等待内容初始化并从中调用createComponent?或者更简单的方法?跨度>

标签: angular


【解决方案1】:

您可以使用以下 sn-p 将动态创建的组件转发给子组件:

const componentRef = this.tableHead.viewContainer.createComponent(rowFactory);
this.tableHead.viewContainer.element.nativeElement
                .appendChild(componentRef.location.nativeElement);

Forked Stackblitz

【讨论】:

    猜你喜欢
    • 2017-02-24
    • 1970-01-01
    • 2022-07-21
    • 2017-09-10
    • 2017-07-07
    • 2020-12-29
    相关资源
    最近更新 更多