【发布时间】: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.directive 和 ui-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