I am creating a "component factory" to help me create Components dynamically. This factory is used to create Components like; PopOvers, Modals, Overlays etc.
It has a attach method to create Components:
attach<T>(component: ComponentType<T>, viewContainerRef: ViewContainerRef): ComponentRef<T> {
let componentFactory =
this.componentFactoryResolver.resolveComponentFactory(component);
let ref = viewContainerRef.createComponent(
componentFactory,
viewContainerRef.length,
viewContainerRef.parentInjector);
return ref;
}
The method accepts the type of the Component I want to create, and what ViewContainer it should be added to.
When calling this method from inside of a Component, I call it with the Components ViewContainer. And this works fine!
But I would like to have the option to specify if the new Component should be created in the "root" ViewContainer ie. the body of the HTML.
Is this possible? I'm really new to Angular2 so maybe I'm really off track and should solve this some other way.
You could implement some module which is providing root component reference to anyone interested.
So first of all create that module, put it into injector.
As that is done require that module from injector within your application root, the one you are bootstrapping and register your root component with it (that I'm afraid will the closest thing to root as you can get as window just doesn't implement ElementRef).
As that is done you can inject that modules in any sub component, ask for root element reference and do whatever you please with it.
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