Angular CDK Overlay:如何计算投影内容height/width

Angular CDK Overlay: how to calculate projected content height/width

我正在使用 Angular CDK 覆盖。配置中的属性之一是 FlexibleConnectedPositionStrategy。我正在尝试在我的点击触发器之上附加叠加层。当顶部有足够的 space 以适应覆盖时,一切正常。我想做的是检查顶部是否没有足够的 space 然后将叠加层附加到触发器的底部。为此,我在调用 Overlay.open(...) 后需要一些方法来访问投影内容,以便计算它的尺寸。有办法吗?

到目前为止,我只看到访问内部 _projectedViews[] 数组的骇人听闻的方式,但未看到其未记录的功能。试图找到更清洁的方法。

Andrei,当您定义 cdk-overly 时,您选择 "positionStrategy"。位置的顺序在数组 withPositions 中定义。可以看到这个link(不知道是不是有点过时了):netanet basal cdk overlay (really the Angular material cdk-overlay is very poor), that I try to simply in this

通常您导入叠加层和 overlayPositionBuilder

constructor(public overlay: Overlay)

您使用 create

创建了 overLayRef
const overlayRef = overlay.create();

函数 create 是 OverlayConfig with properties: Height, width, maxWidth,.. and (among others) positionStrategy, that is an object of type PositionStrategy

类型的对象

因此,首先创建一个 PositionStrategy 类型的对象。为此,您可以使用 overlay

的方法 position()

这个对象有方法 flexibleConnectedTo

你可以选择"connected"到ElementRef | HTML元素| Point & { width?: number;高度?:数字;};

this return a FlexibleConnectedPositionStrategy that you can give value to positions (an array of ConnectionPositionPair), 或直接或使用方法 withPositions

所以,例如

const positionStrategy = this.overlayPositionBuilder
      .flexibleConnectedTo({ x, y })
      .withPositions([{
        originX: 'center',
        originY: 'top',
        overlayX: 'center',
        overlayY: 'bottom',
      },
      {
        originX: 'center',
        originY: 'bottom',
        overlayX: 'center',
        overlayY: 'top',
      }]);

首先尝试附加到顶部,但如果没有足够的space使用第二个定义的位置

更新

好吧,最终位置可以在执行附加后包含在 setTimeout() 中,例如

   //After attach
   this.overlayRef.attach(new TemplatePortal(menu, viewContainerRef, {
            $implicit: data, close:this.close
        }));
    //enclosed in a setTimeout() we has this.overlayRef.overlayElement
    setTimeout(()=>{
      console.log(this.overlayRef.overlayElement.getBoundingClientRect())
    })