Carl Lindth
Carl Lindth

Reputation: 57

How to access the "root" ViewContainerRef from a component

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.

Upvotes: 3

Views: 6224

Answers (2)

Martin Nuc
Martin Nuc

Reputation: 5764

You can save view ref in root component and then inject ApplicationRef. Take a look on this issue:

https://github.com/angular/angular/issues/6446#issuecomment-173459525

it's described there how to do it exactly.

Upvotes: 1

zii
zii

Reputation: 227

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.

Upvotes: 2

Related Questions