How to dynamically add angular components to the DOM without a pre-determined ViewContainerRef?
Asked Answered
P

1

7
  • This is a solution I found that I think will be useful to others.

  • This can be applied to any native element that does not have a ViewContainerRef set on it.

I am trying to implant an angular component inside a table (Tabulator v4.2) on a click event. The table is being created dynamically by a plugin, so I do not have access to the DOM elements I need to set an angular ViewContainerRef for. In the click event callback, I have access to the element I wish to add the angular component to.

How do I add the angular component to that element without an angular ViewContainerRef set on it?

Each click should create a new component and set it inside the given DOM element.

Porphyria answered 17/4, 2019 at 13:51 Comment(0)
P
2

I solved it using the Angular renderer and Angular dynamic components. Angular Dynamic Component Loader

Parent component HTML

<ng-template #willContainTheChildComponent></ng-template>

Parent component class

@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);
            }
Porphyria answered 17/4, 2019 at 14:2 Comment(3)
Thanks, this is very usefull with Tabulator in angular. Great solution!Lipid
You asked for solution "without pre-determined ViewContainerRef" but <ng-template #willContainTheChildComponent></ng-template> IS the pre-determined ViewContainerRef. Why to reinvent the wheel with the Renderer then?Marius
@Marius I need it to be able to instantiate an angular component. Is there a way to immediately set an angular component in the given element from the callback?Porphyria

© 2022 - 2024 — McMap. All rights reserved.