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是下拉选项展示给用户的文本字段,对应数据中的namebindValue是选中后存入表单的实际值字段,对应数据中的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
相关产品推荐
相关产品推荐

