Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a component into a elementref?

Tags:

angular

I want to add a component into a elementref as a child and have access to it's properties.

const element: HTMLElement = document.createElement('div');

element.innerHTML = // Component needs to be added here

// Need to have access to properties of the Component here

I have added a Full Calendar to my project and for the timeline i need to add custom resource Elements. For this i only get access to the HTMLElement and some data. So What i want to do is pass an intialised component to the HTMLElement.

Right now my only option is writing the html as the string and passing it to the innerHTML. Is there a better Option?

like image 307
Sachith Rukshan Avatar asked Jan 02 '20 10:01

Sachith Rukshan


1 Answers

In one of my projects, I achieved something similar to your requirement this way. Let me know if it helps?

constructor(private componentFactoryResolver: ComponentFactoryResolver,
            private injector: Injector, 
            private appRef: ApplicationRef) {
  const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); // Your dynamic component will replace DynamicComponent

  const componentRef = componentFactory.create(this.injector);

  this.appRef.attachView(componentRef.hostView);  

  const domElem = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;

  const element: HTMLElement = document.createElement('div');
  element.appendChild(domElem); // Component needs to be added here
  document.body.appendChild(element);
}

This way you will have reference to your dynamic component as componentRef

like image 151
prabhatojha Avatar answered Nov 13 '22 04:11

prabhatojha