How to fit overly dynamic component width using CKD overly

I’m building a kind of tags input and I’m using the CKD overly.
the dynamic component should be open under the origin input and should fit to the input width.
I do success to position the dynamic component under the input but I don’t know how to make it fit to the input width.

My code

     open<T>(component: ComponentType<T>, config: OverlayConfig, origin: FlexibleConnectedPositionStrategyOrigin): any {
        this.overlayRef = this.overlay.create({
          positionStrategy: this.getPositionStrategy(origin),
          hasBackdrop: true,
          backdropClass: 'cdk-overlay-transparent-backdrop'
        });
        const componentPortal = new ComponentPortal(component);
        return {
          comRef: this.overlayRef.attach(componentPortal),
          overlayRef: this.overlayRef
        };
      }

      getPositionStrategy(origin: FlexibleConnectedPositionStrategyOrigin): any {
        return this.overlay.position().flexibleConnectedTo(origin).withDefaultOffsetY(5).withPositions([
          BOTTOM_POSITION_ALIGN_TO_ORIGIN
        ]).withPush(false);
      }

Snapshot
The upper image is how it look now and the below is how I want it to be

Please let me know if cdk overly can help with it or I should add to my dynamic component a with input
and set it by my self?

Hey, as I see your issue the easiest way to set an appropriate width to the overlay element is to set it manually.

const componentRef: ComponentRef = this.overlayRef.attach();
componentRef.instance.width = inputWidth;

And then, apply that width inside of the component using hostbindings:

export class MyComponent {
  @HostBinding('style.width.px')
  @Input()
  width = 0;
}

Or using a declarative approach with portals:

<my-select *cdkPortal [style.width.px]="inputWidth"></my-select>
@ViewChild(CdkPortal) portal: CdkPortal;

show() {
  this.overlayRef.attach(this.portal);
}
3 Likes