Jacques Murray
Jacques Murray

Reputation: 11

Ng-Select Selected are not updating from ngModel

I'm experiencing a problem that has me stumped. I have an ng-select. When loading records to the ngModel, it doesn't change the ng-select. The weirdest part is that on another page, the same code works.

I've tried numerous different options, even creating new arrays just to test. Also tried setTimeout to see if something is clearing the selection.

The HTML code

  <label>
    Add a Secondary channel
  </label>
  <br />
  <ng-select placeholder="Select schools" items="schoolsArray" [(ngModel)]="selectedSecondSchools" [multiple]="true" name="secondSchools"
  #secondSchools="ngModel">
  </ng-select>
</div>

The one function in the component. The array is declared as selectedSecondSchools[] = [];

getVodEventGameSecondaryChannels(vodEventId: number, vodEventGameId: number): string[] {
    let schoolIds: string[] = [];

    this.vodEventService
      .getVodEventGameSecondaryChannelsByGameId(vodEventId, vodEventGameId)
      .subscribe((sc: IVodEventGameSecondaryChannels[]) => {
        sc.forEach(gsc => {
          schoolIds.push(
            gsc.schoolId.toString());
        });
      });

    this.eventGame.gameSecondaryChannelIds = schoolIds;
    this.selectedSecondSchools = schoolIds;

    return schoolIds;
  }

When the data is returned, the returned IDs need to be selected within the ng-select and displayed.

Upvotes: 1

Views: 5326

Answers (1)

Pupundra
Pupundra

Reputation: 11

It depends on the type of schoolsArray. In your case, I guess, schoolsArray is a list of objects, while ngModel is an array of strings. ng-select doesn't know how to map strings from ngModel to objects from items.

Please see documentation for property bindValue to inform ng-select how to bind items keys to the model. https://github.com/ng-select/ng-select

To summarize, add bindValue="id-property-name-in-items" to ng-select tag.

Upvotes: 1

Related Questions