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

Angular使用ngx-chips时如何获取TagModel值及解决类型报错

报错原因

ngx-chips 内置的TagModel是string | Record<string, any>联合类型:

  • 当你使用纯字符串形式存储标签时,onAdd返回的值就是string类型,本身没有value属性
  • 当你使用对象形式存储标签时,对象的键名也没有默认的value字段,取决于你自定义的字段或者组件配置的identifyBy/displayBy参数
解决方法
  • 方法1:先做类型收窄再取值
addInternalDomain(tagText: TagModel) {
  // 纯字符串标签直接使用返回值
  if (typeof tagText === 'string') {
    console.log(tagText)
    return
  }
  // 对象类型标签根据实际存储的字段取值,例如存储字段为name/value时对应取值即可
  console.log(tagText.value ?? tagText.name)
}
  • 方法2:对齐组件配置的字段取值
    如果在tag-input组件上配置了identifyBy和displayBy参数,直接用你配置的字段名取值即可,示例如下:
    HTML代码:
<tag-input
  class="martop20 tag-adder width100 heightauto"
  [onAdding]="onAdding"
  (onAdd)="addInternalDomain($event)"
  type="text"
  identifyBy="domain"
  displayBy="domain"
>

对应TS代码:

addInternalDomain(tagText: TagModel) {
  if (typeof tagText !== 'string') {
    console.log(tagText.domain)
    return
  }
  console.log(tagText)
}
  • 方法3:自定义类型覆盖默认定义
    如果项目内所有标签都使用固定结构的对象,可以自定义类型避免每次类型收窄:
// 自定义标签类型,字段和你实际存储的结构对齐即可
type CustomTagModel = {
  value: string
  id?: number
}

addInternalDomain(tagText: TagModel) {
  const tag = tagText as CustomTagModel
  console.log(tag.value)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:18:00