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

Angular14中无[(ngModel)]使用ng-multiselect-dropdown单选报错求助

解决方案:Angular 14 ng-multiselect-dropdown单选模式无初始值报错问题

问题原因

ng-multiselect-dropdown组件在单选模式下,内部逻辑依赖双向绑定的变量管理选中状态,即便不需要初始值,也必须绑定一个变量接收选中项,否则选择时会因找不到状态载体抛出错误。

修复步骤

  1. 在组件类声明选中项变量
    在TypeScript代码中添加用于接收选中值的变量,初始值设为null或undefined即可:
selectedItem: any = null;
  1. 模板中绑定ngModel
    修改HTML模板,添加[(ngModel)]绑定到上述变量,同时确保dropdownSettings中已开启单选模式:
<ng-multiselect-dropdown
  [placeholder]="'search the country'"
  [settings]="dropdownSettings"
  [data]="dropdownList"
  [(ngModel)]="selectedItem">
</ng-multiselect-dropdown>
  1. 确认dropdownSettings配置
    保证你的dropdownSettings中正确开启单选模式:
dropdownSettings = {
  singleSelection: true,
  // 其他自定义配置项
};

完成以上修改后,组件会正常显示占位符,选择选项时不会触发报错,选中的值会自动存入selectedItem变量中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:48:21