ng2-select2 icon indicating copy to clipboard operation
ng2-select2 copied to clipboard

When data changes the value on select gets overriden with the first value in the 'data' list

Open igimenez opened this issue 6 years ago • 6 comments

Hi guys,

I am having a problem. When my select2 is populated with countries the valueChanged is being triggered with the first element of the countries list. Doing some digging I found that when the countries collection changes (from [] to a collection of countries), the whole select is distroyed and a new is created. And the newly created loads the first element of the data list as its value.

<select2 #countryInput="ngModel" name="country" [data]="countries" [width]="'100%'" [options]="selectOptionsCountry" (valueChanged)="formObj.countryCode = $event.value" [(ngModel)]="formObj.countryCode" ngDefaultControl required> <option></option> </select2>

Does anybody have found a workaround for this??

Btw, the workaround I find is to make sure the countries are loaded before the formObj I am editing, but that's kinda hackky, looking for a better solution.

Thanks

igimenez avatar Sep 13 '18 00:09 igimenez

I have the same problem, some solution?

hassegawa avatar Feb 03 '19 02:02 hassegawa

I have the same problem, any way to solve?

senhorlopes avatar Feb 03 '19 06:02 senhorlopes

I have the same problem

LucasLopesr avatar Feb 03 '19 11:02 LucasLopesr

the pr #134 solved it.

hassegawa avatar Feb 05 '19 00:02 hassegawa

until hassegawa's fix gets merged in I found a workaround solution that may be useful. I set my processResults option to this:

'processResults': function (data) {
          var results = [];
          const epochTime = (new Date).getTime();
          // work around for issue https://github.com/NejcZdovc/ng2-select2/issues/136 (use epoch time to get unique ids.
          for (var i = 0; i < data.results.length; i++ ) { results.push( { "id": i + epochTime, "text": data.results[i]} ); }
          return { 'results': results };
}

The above snippet makes use of epoch time to ensure that each option is given a unique id.

redcricket avatar Apr 30 '19 21:04 redcricket