首页 > 解决方案 > Ng-Select Selected 未从 ngModel 更新

问题描述

我遇到了一个让我难过的问题。我有一个 ng-select。将记录加载到 ngModel 时,它不会更改 ng-select。最奇怪的部分是在另一个页面上,相同的代码可以工作。

我尝试了许多不同的选项,甚至创建新数组只是为了测试。还尝试了 setTimeout 以查看是否有某些东西正在清除选择。

HTML 代码

  <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>

组件中的一个功能。数组声明为 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;
  }

返回数据时,需要在 ng-select 内选择返回的 ID 并显示出来。

标签: javascriptangulartypescriptangular-ngselect

解决方案


这取决于schoolsArray. 我猜在你的情况下,schoolsArray是一个对象列表,ngModel而是一个字符串数组。ng-select 不知道如何将字符串从 映射ngModelitems.

请参阅属性文档bindValue以告知 ng-select 如何将items键绑定到模型。https://github.com/ng-select/ng-select

总结一下,添加bindValue="id-property-name-in-items"到 ng-select 标签。


推荐阅读