gpt4 book ai didi

angular - 从 CDK Overlay Portal 获取对组件的引用

转载 作者:太空狗 更新时间:2023-10-29 17:17:04 25 4
gpt4 key购买 nike

我正在使用一项服务,通过组件门户实例化 Angular Material CDK Overlays。

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

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

我已经搜索了文档和源代码,找不到实现它的方法。我可能不得不求助于将来自服务的回调注入(inject)到极其困惑的组件中。

有人知道怎么做吗?

最佳答案

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

参见 OverlayRef source code 中的第 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();

关于angular - 从 CDK Overlay Portal 获取对组件的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com