我试图在一个表格内插入一个角度组件(Tabulator v4.2)。该表是由插件动态创建的,因此我无法访问设置角度ViewContainerRef所需的DOM元素。在click事件回调中,我可以访问我想要添加角度组件的元素。
如何在没有设置角度ViewContainerRef的情况下将角度组件添加到该元素?
每次单击都应该创建一个新组件并将其设置在给定的DOM元素中。
我使用Angular渲染器和Angular动态组件解决了它。 Angular Dynamic Component Loader
父组件HTML
<ng-template #willContainTheChildComponent></ng-template>
父组件类
@ViewChild('willContainTheChildComponent', {read: ViewContainerRef}) willContainTheChildComponent: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver,
private renderer: Renderer2) {
}
//The click handler
onClick: (e, row) => {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(TheComponentClass);
const component = this.willContainTheChildComponent.createComponent(componentFactory);
//Here I have access to component.instance to manipulate the class' contents
this.renderer.appendChild(row.getElement(), component.location.nativeElement);
}