3

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?

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
vicatcu
  • 5,407
  • 7
  • 41
  • 65

2 Answers2

6

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.

Haijin
  • 2,561
  • 2
  • 17
  • 30
  • 1
    ah interesting, that's a creative solution... i'll give it a try and give others a chance to offer alternatives. – vicatcu Mar 02 '19 at 22:37
  • 1
    This definitely put me on the right track, thanks! I followed it through, and with a little guidance from https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript and the use of innerText on the "visibility: hidden" div, I was able to calculate the width dynamically as you suggested (by including a fixed addition to the empirically measured text width and some fudge-factor) – vicatcu Mar 04 '19 at 14:50
  • 1
    I guess I did not thought of the intricacies of getting the width. Glad you figured it out. – Haijin Mar 04 '19 at 16:02
3

adding ng-select { .ng-dropdown-panel { width: auto !important; } } in CSS, it works but I would like to suggest adding a tooltip while hovering making a substring than adding css.

<ng-template ng-option-tmp let-item="item">
        <div [ngbTooltip]="item.length > 15 ? item : ''" container="body">
          {{item.length > 15 ? (item| slice:0:15) + '..' : item}}
        </div>
</ng-template>
Sumit Shrestha
  • 356
  • 3
  • 6