Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to component from CDK Overlay Portal

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?

like image 332
dudewad Avatar asked Mar 03 '18 01:03

dudewad


People also ask

How does a component check its sub component and view it by getting a reference to CdkPortal?

A component can use @ViewChild or @ViewChildren to get a reference to a CdkPortal .

How do you customize a CDK overlay pane?

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.

What is overlayRef?

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);

What is CdkOverlayOrigin?

CdkOverlayOrigin. Directive applied to an element to make it usable as an origin for an Overlay using a ConnectedPositionStrategy.


1 Answers

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();
like image 105
Noémi Salaün Avatar answered Oct 19 '22 14:10

Noémi Salaün