Always selecting first item on dropdown open

Hi everyone !!

I’m using Select2 v4.0.3 implemented in Angular 5 application.

Because of the application’s requests, I needed to bind whole Angular object/model to dropdown’s id (value) and to do that I had to stringify my objects.

So, now the dropdown works fine: we can see object’s title as a text and whole object is stringified as a dropdown’s id (value).

The problem is that somewhere in Select2.js script there is a compare of a selected Id values and it doesn’t recognize my stringify object so it always selects first element and not binded one.

I know that this is not native Select2 behaviour but improvisation, but I really need help to make this work, so if there is someone willing to help me find the line where this can be fixed, I will be very grateful !!

Best Regards,
Josip

Can you post an example of your code on JSFiddle or CodePen or a similar service? You can use dummy datat in your example if you don’t want to expose your actual data.

Hi!

I was able to solve the problem and my binded object is automatically selected on dropdown open.

To do that, I needed to attache select2:open event, re-asign value and trigger internal change event.

$('#myDropdown').on('select2:open', (e: any) => {
  // set binded select2 value again to fix selection on dropdown opening
  $('#myDropdown').val(JSON.stringify(this.selectedValue)).trigger('change.select2');
}

It is working fine now :wink:

Great! I’m glad you found a solution to your problem.