2

I'm trying to add a component dynamically using cdk's ComponentPortal

@Component {
    selector: 'my-app',
    template: '<div #container></div>',
    styleUrls: [ './app.component.css' ]
}
export class AppComponent  {
    @ViewChild('container',  {read: ViewContainerRef, static: false}) container;

    ngAfterViewInit(): void { 
        const dialogContent = new ComponentPortal(BarfooComponent, this.container);
    }
}

DEMO

As you can see from the demo this code doesn't throw any errors, but also renders nothing :(

So, I'm not sure if anything like this is even possible with ComponentPortal and if so I probably miss one or more steps here. Any suggestions how I can do this?

1 Answer 1

1

You have to attach the created component portal. You can do it through the directives like cdkPortalOutlet or manually. CDK Docs Portals - it docs for Portals, which gives the examples on how to do it.

Here is fixed example on stackblitz. Don't forget to include PortalModule from @angular/cdk/portal. This module provides cdkOverlayPortal directive.

Looks like you want to create dialog. Angular CDK provides abstractions for such case: Portals and Overlays.

So the plan is: - create a portal - create an overlay - attach the portal to the overlay

So here is the demo using overlays & portals.

If I remember correctly, you also have to add prebuilt styles from the cdk. You have to add them into architect.build.options.styles array of your angular.json file. You have to add something like node_modules/@angular/cdk/overlay-prebuilt.css there. If you use custom bundle you have to handle it manually.

CDK Docs Overlays - more information about overlays is in the docs.

Sign up to request clarification or add additional context in comments.

9 Comments

Wait! I also added info about overlays. I think if you create dialog it will fit your case.
Thanks a lot, I have it working! One last question, In my case I would like to bind stuff the the components @input and listen to its @Outputs. Is there any way using the cdkPortalOutlet to get access to the instance of the component?
It looks like it is not so hard :) demo
Wait, no setTimeout. this.userSettingsPortal.component is enough. You have it immidiately.
My bad, you are right for this case. Case with overlay attach was in my mind. Here is working demo with overlay attach: stackblitz.com/edit/angular-vyx59e. CdkPortalOutlet has attached output. You can use it. Here is the demo. stackblitz.com/edit/angular-38gvlg Still async, but you don't have magic setTimeout.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.