如何在没有预先确定的ViewContainerRef的情况下向DOM动态添加角度分量?

Yot*_*tam 5 javascript dom angular angular-dynamic-components

  • 我发现这是一个解决方案,对其他人也很有用。

  • 可以将其应用于任何未设置ViewContainerRef的本机元素。

我试图在点击事件中将角组件植入表(Tabulator v4.2)中。该表是由插件动态创建的,因此我无权访问需要为其设置角度ViewContainerRef的DOM元素。在click事件回调中,我可以访问要向其中添加角度分量的元素。

如何在未设置角度ViewContainerRef的情况下向该元素添加角度分量?

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

Yot*_*tam 2

我使用 Angular 渲染器和 Angular 动态组件解决了这个问题。 角度动态组件加载器

父组件 HTML

<ng-template #willContainTheChildComponent></ng-template>
Run Code Online (Sandbox Code Playgroud)

父组件类

@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);
            }
Run Code Online (Sandbox Code Playgroud)

  • 您要求“没有预先确定的 ViewContainerRef”的解决方案,但 `&lt;ng-template #willContainTheChildComponent&gt;&lt;/ng-template&gt;` 是预先确定的 ViewContainerRef。那么为什么要用渲染器重新发明轮子呢? (2认同)