简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM