简体   繁体   English

如何在 Angular 的子组件内动态创建组件?

[英]How to dynamically create component inside child component in Angular?

I am trying to implement something like light version of mat-table form Angular Material.我正在尝试实现类似mat-table形式 Angular 材料的轻型版本。 And i can't create component inside child component.而且我无法在子组件内创建组件。 Here is some code and link to stackblitz at the end.这是最后的一些代码和指向 stackblitz 的链接。

In some *.html file:在某些*.html文件中:

<table uiTable></table>

Base UiTable component:基本 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.directive and ui-table-row.component - just empty angular directive and component with injected ViewContainerRef . ui-table-head.directiveui-table-row.component - 只需清空 angular 指令和注入ViewContainerRef的组件。

I expect that after ngAfterContentInit is done I will get something like我希望在ngAfterContentInit完成后我会得到类似的东西

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

But instead of it i get但我得到的不是它

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

Why?为什么? I call createComponent method from tableHead.viewContainer , but new component creates inside uiTable .我从tableHead.viewContainer调用createComponent方法,但是在uiTable中创建了新组件。 What's wrong?怎么了?

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

You can forward your dynamically created component to children by using the following snippet:您可以使用以下代码段将动态创建的组件转发给子组件:

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

Forked Stackblitz 分叉的 Stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM