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

使用@ng-select/ng-select 9.0.2与Angular14时AddTag功能异常,标签值为null

@ng-select/ng-select 9.0.2 + Angular14 AddTag功能提交值为null的解决方法

问题现象

使用@ng-select/ng-select 9.0.2结合Angular14开发时,开启addTag和multiple模式后,手动添加的标签在UI上正常显示,但提交表单时对应字段的值为null,通过{{formGroup.value | json }}查看表单值也能确认这一点。

问题原因分析

  1. 表单模式混用冲突:同时使用[(ngModel)]和formControlName,Angular中响应式表单与模板驱动表单模式不能混用,会导致值同步逻辑异常。
  2. 新增标签结构不匹配绑定配置:默认addTag生成纯字符串,但ng-select配置了bindLabel="name"和bindValue="value",需要绑定包含这两个属性的对象,纯字符串无法匹配,导致表单值无法同步。
  3. 版本兼容性问题:@ng-select/ng-select 9.0.2官方兼容Angular 12-13,与Angular14存在版本不兼容,可能引发功能异常。

解决方案

1. 移除ngModel,仅保留响应式表单绑定

删除[(ngModel)]="applicable-to-status-codes",响应式表单中只需通过formControlName绑定即可:

<ng-select 
  [items]="[]" 
  [addTag]="addTagFn" 
  [multiple]="true" 
  bindLabel="name" 
  bindValue="value" 
  [closeOnSelect]="false" 
  formControlName="applicable-to-status-codes"
></ng-select>

2. 自定义addTag生成函数,生成匹配结构的对象

在组件类中定义addTagFn,确保新增标签是包含name和value属性的对象:

import { FormGroup, FormControl } from '@angular/forms';

// 自定义标签生成函数
addTagFn = (term: string) => {
  return { name: term, value: term }; // 可根据需求自定义value,比如使用唯一标识
};

// 初始化表单组
formGroup = new FormGroup({
  'applicable-to-status-codes': new FormControl([])
});

3. 升级ng-select到兼容Angular14的版本

建议将@ng-select/ng-select升级到10.0.0及以上版本(官方文档显示10.x+兼容Angular14),执行升级命令:

npm install @ng-select/ng-select@^10.0.0 --save

验证

修改完成后,添加新标签,通过{{formGroup.value | json }}查看表单值,此时applicable-to-status-codes应该能正确显示新增标签的对象数组,提交表单时也能正常获取到值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:01:01