Javascript 动态地将一个组件附加到另一个组件中
这是我的stackblitz链接: 当可视化类型为“table”时,我试图将“table”组件附加到app组件的#test中。为此,我调用Javascript 动态地将一个组件附加到另一个组件中,javascript,angular,typescript,angular6,Javascript,Angular,Typescript,Angular6,这是我的stackblitz链接: 当可视化类型为“table”时,我试图将“table”组件附加到app组件的#test中。为此,我调用createTable(),它创建标记并将其附加到#test div中 标记存在于DOM中,但不存在于table.component.html的内容中(即table works!) 这可能是因为它只是一个标记,而不是一个编译组件 如何获取应用程序组件内部显示的表组件内容?使用ComponentFactoryResolver动态添加组件。这一点在下文中作了进一步
createTable()
,它创建
标记并将其附加到#test div中
标记存在于DOM中,但不存在于table.component.html的内容中(即table works!)
这可能是因为它只是一个标记,而不是一个编译组件
如何获取应用程序组件内部显示的表组件内容?使用
ComponentFactoryResolver
动态添加组件。这一点在下文中作了进一步解释。在stackblitz中添加了完整的解决方案:
. 总之,这就是我所做的:
在app.component.ts
中创建表:
createTable(container) {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TableComponent);
let viewContainerRef = this.insTable.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
// let e = document.createElement("app-table");
// container.appendChild(e);
}
用作和定位点的指令表.directive.ts
:
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[ins-table]',
})
export class TableDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
以及app.component.html
:
<div #charts id="test">
<ng-template ins-table></ng-template>
</div>
试试这个
createTable() {
this.container.clear();
const factory = this.resolver.resolveComponentFactory(TableComponent);
this.componentRef = this.container.createComponent(factory);
}
您的分叉示例:@eko:我尝试过,但似乎对我无效。这种方法可能会出错。你能帮我一个忙吗?你可以在
应用程序组件html
@Exterminator中添加
:我只想在特定的迭代中,当可视化类型=='table'时,才添加表。通过添加标记,表组件将始终显示。创建一个全局变量命名类型—您需要的任何类型—并将*ngif=“type===”table'
添加到
中。我尝试过,但它似乎不适用于我。这种方法可能会出错。你能帮我吗?@IncharaRaveendra请检查我的完整解决方案请检查我希望表格插入到图表中,而不是另一个容器中。你是说在分区内?是的。在该div内的move ng模板内检查stackblitzname。这样做,只需附加一次表组件。请检查appObject,visualization type==table是两次,这意味着graph table应该出现在DOM中。检查我的stackblitz输出,查看是否根据条件插入了两次应用程序表标签
createTable() {
this.container.clear();
const factory = this.resolver.resolveComponentFactory(TableComponent);
this.componentRef = this.container.createComponent(factory);
}