I am using a service to instantiate Angular Material CDK Overlays using Component Portals.
Once I create a portal and attach it to an overlay, is there any way to access the component reference of the component that the portal creates? I want to be able to listen to events of that component from outside. For example:
const portal = new ComponentPortal(MyCoolComponent, /* ...etc */);
this.overlay.attach(portal);
// I'd like to be able to do something like...
// portal.MyCoolComponent.someEventEmitter.subscribe();
I've scoured the docs and the source, can't find a way to do it. I might have to resort to injecting a callback from the service into the component which is extremely messy.
Does anyone know how to do this?
A component can use @ViewChild or @ViewChildren to get a reference to a CdkPortal .
You should use MAT_SELECT_CONFIG injection token . It has an option overlayPanelClass: string | string[] , which represents: the class or list of classes to be applied to the menu's overlay panel. The overlayPanelClass option is available from Angular Material v11.
The OverlayRef is a PortalOutlet - once created, content can be added by attaching a Portal . See the documentation on portals for further information. const overlayRef = overlay.create(); const userProfilePortal = new ComponentPortal(UserProfile); overlayRef.attach(userProfilePortal);
CdkOverlayOrigin. Directive applied to an element to make it usable as an origin for an Overlay using a ConnectedPositionStrategy.
The OverlayRef.attach
method returns a ComponentRef
. A ComponentRef
has a property instance
which is an instance of your component. ComponentRef
can be generic, so you know the type of the inner component.
See line 60 in OverlayRef
source code
attach<T>(portal: ComponentPortal<T>): ComponentRef<T>;
So you can do that in your code
const portal = new ComponentPortal(MyCoolComponent, ...etc);
const compRef: ComponentRef<MyCoolComponent> = this.overlay.attach(portal);
compRef.instance.someEventEmitter.subscribe();
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