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

@ng-select/ng-select用户输入不存在选项时如何将selectedid设为0

ng-select 自定义输入校验实现方案

核心逻辑是同时监听用户输入和选中变更两个场景,每次操作后校验当前值是否存在于绑定的选项列表,不存在则直接将selectedId赋值为0。

1. 组件模板(HTML)配置

<ng-select 
  [items]="optionList"
  bindLabel="name"
  bindValue="id"
  [(ngModel)]="selectedId"
  (search)="handleSearch($event.term)"
  (change)="handleSelectChange($event)"
>
</ng-select>

2. 业务逻辑(TS)实现

首先定义基础变量:

// 绑定的选项列表
optionList = [
  {
    id: '5a15b13c36e7a7f00cf0d7cb',
    name: 'John',
  },
  {
    id: '523675b13c36e7a7f00cf0d7cb',
    name: 'Doe',
  }
];
// 要赋值的选中id变量
selectedId: number | string = 0;

实现搜索输入监听函数:

handleSearch(inputTerm: string) {
  // 输入为空的场景可根据业务需求调整,这里默认赋值为0
  if (!inputTerm.trim()) {
    this.selectedId = 0;
    return;
  }
  // 校验输入内容是否完全匹配选项中的name字段
  const hasMatch = this.optionList.some(item => item.name === inputTerm.trim());
  if (!hasMatch) {
    this.selectedId = 0;
  }
}

实现选中变更监听函数:

handleSelectChange(selectedVal: string) {
  if (!selectedVal) {
    this.selectedId = 0;
    return;
  }
  // 校验选中的id是否真实存在于选项列表
  const isValid = this.optionList.some(item => item.id === selectedVal);
  this.selectedId = isValid ? selectedVal : 0;
}

如果你开启了[addTag]="true"允许用户新增自定义标签,可在addTag回调函数中补充判断逻辑,只要是不属于原有选项列表的新增标签,统一将selectedId赋值为0即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:06:01