Search code examples
angularangular-materialangular-cdk

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?


Solution

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