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?
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.
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.”
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).
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With