Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 render component to body

Tags:

angular

Say I have an Angular2 component <my-button> and I want to give an input for options to render in a dropdown menu shown when the button is clicked. I have the menu component as <my-menu> and it renders conditionally in the template of <my-button> if there are options passed in.

Maybe I can just absolutely position <my-menu> within <my-button> to achieve the desired positioning. But maybe I can't because I have overflow:hidden on a containing element and that would clip <my-menu>. So instead I need to render <my-menu> in <body> and position it absolutely to <my-button>.

Is there a way to render <my-menu> to <body> even though it is placed inside the template for <my-button> instead?

Thanks!

like image 239
Comptonburger Avatar asked Aug 25 '16 05:08

Comptonburger


2 Answers

You can do that, however it is complicated.

  1. Add your dynamic component to module declarations and entryComponents
  2. Get reference to root ViewContainerRef injecting it to your application component.
  3. Get reference to ComponentFactoryResolver, also using injection.
  4. Use something like this:

    private resolverFactory:ComponentFactoryResolver;
    private viewContainer:ViewContainerRef;
    
    var compFactory:ComponentFactory<Frame> = this.resolverFactory.resolveComponentFactory(Frame);
    
    var cmpRef:ComponentRef<Frame> = this.viewContainer.createComponent(compFactory, this.viewContainer.length);
    
  5. Removing component:

    cmpRef.destroy();
    
like image 182
kemsky Avatar answered Nov 15 '22 23:11

kemsky


No, there isn't.

You can bootstrap a component outside your AppComponent and communicate using a shared service instead.

Some discussion about dynamically creating components as sibling to the AppComponent are discussed in https://github.com/angular/angular/issues/9293 but it's not clear if, how, or when this might land.

like image 40
Günter Zöchbauer Avatar answered Nov 16 '22 01:11

Günter Zöchbauer