如何在没有预先确定的ViewContainerRef的情况下动态地将角度组件添加到DOM?

问题描述 投票:4回答:1
  • 这是我发现我认为对其他人有用的解决方案。
  • 这可以应用于没有设置ViewContainerRef的任何本机元素。

我试图在一个表格内插入一个角度组件(Tabulator v4.2)。该表是由插件动态创建的,因此我无法访问设置角度ViewContainerRef所需的DOM元素。在click事件回调中,我可以访问我想要添加角度组件的元素。

如何在没有设置角度ViewContainerRef的情况下将角度组件添加到该元素?

每次单击都应该创建一个新组件并将其设置在给定的DOM元素中。

javascript angular dom angular-dynamic-components
1个回答
4
投票

我使用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);
            }
© www.soinside.com 2019 - 2024. All rights reserved.