Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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.

like image 443
Yotam Avatar asked Apr 17 '19 13:04

Yotam


1 Answers

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);
            }
like image 53
Yotam Avatar answered Oct 26 '22 01:10

Yotam