Search code examples
angularangular-materialoverlayangular-cdk-overlay

Angular - set overlay margin depending on its position strategy


I'm working on a custom overlay component and I need to set a margin on it. It should be 0.5rem depending on the position of the overlay (e.g. originY === 'bottom' => margin-top: 0.5rem, and so on). I was hoping to use PositionStrategy object for this but it looks like there's no such info available on it.

private getOverlayConfig(origin: HTMLElement): OverlayConfig {
  const positionStrategy = this.calculatePosition(origin);
  // was hoping for something like this
  // const panelClass = positionStrategy.originY === 'bottom' ? 'panel-margin-top' : 'panel-margin-bottom'
  return new OverlayConfig({
    positionStrategy,
    panelClass,
    //...
  })
}

PositionStrategy object exposes only four methods (apply, attach, detach, dispose) which are of no use to me and I can't access anything else.

As for a CSS solution I can't imagine it. The overlay can open either a template or a component and since they are placed in an overlay, I have no idea how to compare the position of the overlay with the origin position (button which opened the overlay).

Any idea how to do it?


Solution

  • Turns out you can set the panelClass when providing a position strategy. And it works great.

    private getPositions(): ConnectionPositionPair[] {
      return [
        // This strategy opens the panel below the origin => add margin on top
        {
          panelClass: 'panel-margin-top',
          originX: 'start',
          originY: 'bottom',
          overlayX: 'start',
          overlayY: 'top'
        },
        //...
      ]
    }
    

    Honestly I didn't expect the panelClass to be part of a position object but in a hindsight it make sense.