从 CDK 覆盖门户获取对组件的引用



我正在使用一项服务来使用组件门户实例化角度材料CDK叠加层。

创建门户并将其附加到叠加层后,是否有任何方法可以访问门户创建的组件的组件引用?我希望能够从外部收听该组件的事件。例如:

const portal = new ComponentPortal(MyCoolComponent, /* ...etc */);
this.overlay.attach(portal);
// I'd like to be able to do something like...
// portal.MyCoolComponent.someEventEmitter.subscribe();

我已经搜索了文档和源代码,找不到方法。我可能不得不求助于将来自服务的回调注入到非常混乱的组件中。

有谁知道如何做到这一点?

OverlayRef.attach 方法返回一个ComponentRefComponentRef具有属性instance它是组件的实例。 ComponentRef可以是泛型的,因此您知道内部组件的类型。

请参阅源代码OverlayRef第 60 行

attach<T>(portal: ComponentPortal<T>): ComponentRef<T>;

所以你可以在代码中做到这一点

const portal = new ComponentPortal(MyCoolComponent, ...etc);
const compRef: ComponentRef<MyCoolComponent> = this.overlay.attach(portal);
compRef.instance.someEventEmitter.subscribe();

最新更新