【问题标题】:Get reference to component from CDK Overlay Portal从 CDK 覆盖门户获取对组件的引用
【发布时间】:2018-03-03 01:56:13
【问题描述】:

我正在使用服务来使用组件门户实例化 Angular Material 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();

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

有人知道怎么做吗?

【问题讨论】:

标签: angular angular-material angular-cdk


【解决方案1】:

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

【讨论】:

  • 我会在星期一检查这个。谢谢,可能只是有点脑筋急转弯:)
  • 我的天啊。是的,这是正确的。谢谢。 眼球
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多