Get reference to component from CDK Overlay Portal
Asked Answered
G

1

11

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?

Good answered 3/3, 2018 at 1:56 Comment(3)
Thу answer is here: github.com/angular/material2/issues/3593 :)Titty
lol the answer is also down below, accepted about 6 months ago :DGood
I know, but this issue is much better :)Titty
V
30

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();
Vandyke answered 3/3, 2018 at 10:4 Comment(2)
I will check this out on monday. Thanks, probably was just a little brainfried :)Good
My god duh. Yes this was correct. Thanks. eyerollGood

© 2022 - 2024 — McMap. All rights reserved.