我正在使用 ngx-datatable 创建一个可重用的数据表,我希望在行细节内呈现动态组件。数据表组件从父模块接收组件类作为参数,我使用 ComponentFactory 来创建组件。我可以看到构造函数和 onInit 方法正在为动态组件运行,但它没有附加到 DOM。
这是 datatable html 中 row-detail 的样子:
<!-- [Row Detail Template] -->
<ngx-datatable-row-detail rowHeight="100" #myDetailRow (toggle)="onDetailToggle($event)">
<ng-template let-row="row" #dynamicPlaceholder let-expanded="expanded" ngx-datatable-row-detail-template>
</ng-template>
</ngx-datatable-row-detail>
<!-- [/Row Detail Template] -->
Run Code Online (Sandbox Code Playgroud)
这就是我的 .ts 文件的样子:
@ViewChild('myDetailRow', {static: true, read: ViewContainerRef}) myDetailRow: ViewContainerRef;
@ViewChild('dynamicPlaceholder', {static: true, read: ViewContainerRef}) dynamicPlaceholder: ViewContainerRef;
renderDynamicComponent(component) {
var componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
var hostViewConRef1 = this.myDetailRow;
var hostViewConRef2 = this.dynamicPlaceholder;
hostViewConRef1.createComponent(componentFactory);
hostViewConRef2.createComponent(componentFactory);
}
Run Code Online (Sandbox Code Playgroud)
还有一点是,如果我的#dynamicPlaceholderng-template 放在 ngx-datatable 之外,它就可以工作,并且动态模块会被渲染和显示。