angular - 如何在Angular中的子组件内动态创建组件?
问题描述
我正在尝试实现类似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>
为什么?我从 调用createComponent
方法tableHead.viewContainer
,但在内部创建了新组件uiTable
。怎么了?
Stackblitz 链接 - https://stackblitz.com/edit/ui-table
解决方案
您可以使用以下代码段将动态创建的组件转发给子组件:
const componentRef = this.tableHead.viewContainer.createComponent(rowFactory);
this.tableHead.viewContainer.element.nativeElement
.appendChild(componentRef.location.nativeElement);
推荐阅读
- javascript - 如何在 React Hooks 中使用 componentWillMount()?
- laravel - Lumen/Laravel 从 Http Header 获取参数值
- python-3.x - 在数组中创建一组随机数字,而同一数字连续重复三次
- python - 输入 [] 出错:findDistance() 接受 0 个位置参数,但给出了 1 个
- reactjs - 强制在方法中重复变量
- database - 仅出现在功能依赖关系的 RHS 上的属性可以是主要属性吗?
- php - PHP - 我在下载高文件时遇到问题
- react-native - 做某事后如何插入服务器
- python - 错误,因为字节无法编码?
- c++ - 使用给定的参数信息创建一个新节点并添加一个新节点