首页 > 解决方案 > 如何在Angular中的子组件内动态创建组件?

问题描述

我正在尝试实现类似mat-tableAngular 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>

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

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

标签: angular

解决方案


您可以使用以下代码段将动态创建的组件转发给子组件:

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

分叉的 Stackblitz


推荐阅读