Search code examples
cssangularionic-frameworkwidthangular-ngselect

make ng-select width adjust to selected items / available options?


I'm using ng-select in an Ionic3 / Angular5 project and I'm using its multiple selection configuration. The presentation of the select input is always considerably wider than it needs to be to contain the selected items or any of the available options.

I'd like it to be sized such that the width is at least the maximum width the component would have if any one of the available options were selected, and such that the otherwise the width is whatever is required to contain the actively selected options.

Is it possible to get ng-select to behave in that way?


Solution

  • I am not sure if ng-select has any build-in way to do what you want. But it is a block element which means you can control its width as you want. And in Angular, you can dynamically control style with ngStyle. For Example: define a getWidth() function with ngStyle.

      <ng-select [items]="items"
               [ngStyle]= "{width:getWidth()}"
               >
      </ng-select>
    

    Now in getWidth function, you can return any value you want to control the width. you can loop through the items, and get maximum length of item, then translate into pixels. there's a ratio of string length to pixel which you might need to experiment. And you can also listen to events and return the width based what is currently selected.