Home > other >  Passing data to and from a ComponentPortal in Angular CDK
Passing data to and from a ComponentPortal in Angular CDK

Time:12-13

I have tried to use the method found at Angular CDK: How to set Inputs in a ComponentPortal but PortalInjector seems to be deprecated, with no actual instructions on what to do in its place. The deprecation warning states to "Use Injector.create instead." with but not how or where to use it or what it's actually replacing.

I have also tried to wrap my head around Material's own Dialog component to see if I could figure out how they did it, but nothing.

So I pose the question again for Angular 13:

How can I pass data into and out of a component that was created using a ComponentPortal()? If the answer is something generic such as using an Injector, can you please point me to an example or documentation on how to do so? A 'hello world' of passing Injectors?

CodePudding user response:

IMHO, we do not have a straightforward way to have something that we do as an Input or Output from componentportal.

What you can do is to pass the data which you want to use as @Input using the attached event of portal.

Check this demo code where we are passing value to Guest component.

<ng-template (attached)="onComponentRendering($event)" [cdkPortalOutlet]="guestPortal"></ng-template>

and then using it as

 public onComponentRendering(ref): void {
    ref = ref as ComponentRef<any>;
    ref.instance['guestData'] = [ ...something];
 }

For output data, you can create a service (with Subject) and use it to communicate between components.

  • Related