Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: How to dynamically create ViewContainerRef

I'm trying to create modal service with ability to show arbitrary modal. Currently, to create dynamic component, I'm storing placeholder for it in view:

 <div #container></div>
 ...
 @ViewChild("dialogContainer", {read: ViewContainerRef})
 dialogContainer:ViewContainerRef;

And than creating component:

let factory = this.componentResolver.resolveComponentFactory(Dialog);
this.componentReference = this.dialogContainer.createComponent(factory);

Is there way to move all this logic out of component to service, with ability to create/remove view container in body, or any other DOM element?

like image 803
lexigren Avatar asked Oct 31 '16 12:10

lexigren


People also ask

Can we create component dynamically in Angular?

If we go by the Angular definition, a factory component Angular is a base class for a factory that can create a component dynamically. Instantiate a factory for a given type of component with resolveComponentFactory(). Use the resulting ComponentFactory. create() method to create a component of that type.

How do I get ViewChild ViewContainerRef?

Get ViewContainerRef with ViewChild: We can use the ViewChild decorator to grab any element in our view and read him as ViewContainerRef . In this example, the container element is the “div” element, and the template will be inserted as a sibling of this “div.”

Which method of ViewContainerRef create an instance of a component?

Descriptionlink. Can contain host views (created by instantiating a component with the createComponent() method), and embedded views (created by instantiating a TemplateRef with the createEmbeddedView() method).


1 Answers

It dosen't create ViewContainerRef but It helps you create dynamically a popup window as separate Component.

I created plunker example for you, and I didn't embed it here because stackowerflow code snippet dosen't support all features which I need in order to create example :) http://embed.plnkr.co/XFQAAHDAyrRAih3RTvHH/

like image 111
igorzg Avatar answered Sep 18 '22 10:09

igorzg