How do I add a position strategy to an Angular CDK overlay?
there is at least two errors in your example :
1/ the method create exist on class Overlay not (OverlayContainer)
2/ ConnectedPositionStrategy is not an object, its a typescript interface ( that why you get error ... typeof ConnectedPositionStrategy ... )
then the best way to create a "connected" overlay is to use the OverlayPositionBuilder ( here the doc, but this will not help much )
If you scan angular material repo you will see some example, like in the datepicker who use :
.connectedTo(this._datepickerInput.getPopupConnectionElementRef(), { originX: 'start', originY: 'bottom' }, { overlayX: 'start', overlayY: 'top' })
so you can certainly use this snippet by replacing this._datepickerInput.getPopupConnectionElementRef() by your component elementRef
constructor (
...
private overlay: Overlay
) {}
showOverlay() {
let overlay = this.overlay.create({
positionStrategy: this.overlay.position().connectedTo(<yourElRef>, { originX: 'start', originY: 'bottom' }, { overlayX: 'start', overlayY: 'top' })
});
}
After some search including this post. I have come with an updated solution for the use of cdk overlay for menus and others with the conected position strategy. (using flexible since conected show deprecated decoration)
const positionStrategy = this.overlay.position()
.flexibleConnectedTo(elementRef)
.withPositions([{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top',
}, {
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom',
}]);
Then add a scroll strategy for your needs, for example reposition in case you want your menu to reposition on scroll
scrollStrategy: this.overlay.scrollStrategies.reposition()
But if your scroll is not on the main body, you need to add the cdk-scrollable directive from
import {ScrollingModule} from '@angular/cdk/scrolling';
to
<div class="your-scroll-container" cdk-scrollable>