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

Yotam
  • 97
  • 7

1 Answers1

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);
            }
Yotam
  • 97
  • 7
  • Thanks, this is very usefull with Tabulator in angular. Great solution! – Shaul Naim Apr 18 '19 at 06:06
  • 2
    You asked for solution "without pre-determined ViewContainerRef" but `` IS the pre-determined ViewContainerRef. Why to reinvent the wheel with the Renderer then? – Dimanoid Nov 08 '19 at 09:18
  • 1
    @Dimanoid 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? – Yotam Dec 01 '19 at 11:11