Search code examples
angularangular-materialangular-cdk

Angular CDK - overlay attach to target while scrolling


I am trying to implement an Overlay with the Angular CDK. The Overlay is used inside a container that has a horizontal scroll. If we scroll to the left side the overlay should stick to the original position or disappear.

I could successfully implement this behavior by using the CDK directives. (Open the overlay by clicking on the open button and scroll to the left). The overlay follows the button.

Stackblitz example that uses the directives

I try to achieve the same without the directives but with the usage of the Overlay service.

Stackblitz example that uses the services

In this case, the overlay stays and doesn't move with the content. I need to use the service over the directive because we will encapsulate this behind a custom directive. Any ideas on how to achieve the same behavior with the services as with the directives are very welcome? Thx in advance.


Solution

  • I think you should be able to achieve that behavior with the following configuration:

    this.overlayRef = this.overlay.create({
      scrollStrategy: this.overlay.scrollStrategies.reposition(), // remove autoClose: true option
      hasBackdrop: false,
      positionStrategy: this.overlay
        .position()
        .flexibleConnectedTo(this.button)
        .setOrigin(this.button)
        .withScrollableContainers([this.scrollContainer])
        .withPositions([                                         // correct this as you want
          {
            originX: "start",
            originY: "bottom",
            overlayX: "start",
            overlayY: "top"
          }
        ])
        .withFlexibleDimensions(false)                          // add this
        .withPush(false)                                       // add this
    }); 
    

    Forked Stackblitz