You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 12中ng-select下拉列表加载API数据后显示空白如何解决

问题解决办法

存在两处配置错误,修正后即可正常显示:

1. 修正Component层数据赋值字段

API返回的车辆品牌数组存放在results.vehiclemakes字段下,原代码取值字段错误,修改loadAllVehicles方法:

loadAllVehicles() {
  this.vehiclemodelService.getParameters().subscribe(
    data => {
      // 替换原错误的data.results.vehicles
      this.vehicles = data.results.vehiclemakes;
    },
    error => {
      this.store.dispatch(loadErrorMessagesSuccess(error));
    }
  );
}

2. 修正ng-select绑定属性

原代码bindLabel绑定的make_id字段不存在于返回的品牌对象中,且bindValue和bindLabel功能搞反:

  • bindLabel是下拉选项展示给用户的文本字段,对应数据中的name
  • bindValue是选中后存入表单的实际值字段,对应数据中的id
    修改后的HTML代码如下:
<ng-select [items]="vehicles"
   [selectOnTab]="true"
   [searchable]="true"
   bindValue="id"
   bindLabel="name"
   placeholder="Select Vehicle Make"
   [multiple]="false"
   [clearable]="true"
   required
   formControlName="make_id">
</ng-select>

可选优化建议

建议给车辆品牌定义明确的类型接口,替代any类型,提升类型安全性:

interface VehicleMake {
  id: number;
  name: string;
}
// 替换原vehicles!: any[]
vehicles!: VehicleMake[];

内容的提问来源于stack exchange,提问作者user11352561

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:21:03