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
相关产品推荐
相关产品推荐

