不使用[(ngModel)]时如何通过代码为tag-input组件添加、清除chips
实现方案
你当前已经通过响应式表单的formControlName="chips"完成了组件绑定,不需要依赖ngModel即可实现编程式操作,以下是两种可行方案:
方案1:直接操作绑定的FormControl(推荐)
直接操作和组件绑定的chips表单控件的值,即可同步更新组件的标签展示,无需额外获取组件实例:
组件类代码示例
// 假设你已在组件中定义了对应的响应式表单实例 public form = this.fb.group({ chips: [[]] // 初始值为空数组对应无标签 }) // 清空所有标签 clearChips() { this.form.get('chips')?.setValue([]) } // 插入自定义标签 addCustomChip(customTag: {value: string, display: string}) { // 先获取当前已有标签列表 const currentTags = this.form.get('chips')?.value || [] // 拼接新标签后赋值(用扩展运算符生成新数组触发变更检测) this.form.get('chips')?.setValue([...currentTags, customTag]) }
模板按钮绑定示例
<button type="button" (click)="clearChips()">清空所有标签</button> <button type="button" (click)="addCustomChip({value: 'custom_val', display: '自定义展示名'})">插入自定义标签</button>
注意:你配置了
identifyBy="value"、displayBy="display",插入的标签对象必须包含这两个字段,否则组件无法正常识别展示。
方案2:通过模板引用获取组件实例操作
如果你需要触发组件内置的onAdd等绑定事件,可直接调用tag-input组件的原生方法:
第一步:给模板中的tag-input添加引用标识
<tag-input #tagInputRef [formControlName]="'chips'" <!-- 原有其他属性保持不变 --> ></tag-input>
第二步:组件类中获取实例调用方法
import { ViewChild } from '@angular/core' import { TagInputComponent } from 'ngx-chips' // ... @ViewChild('tagInputRef') tagInput!: TagInputComponent // 清空所有标签 clearChips() { this.tagInput.removeAll() } // 插入自定义标签 addCustomChip(customTag: {value: string, display: string}) { this.tagInput.appendItem(customTag) }
内容的提问来源于stack exchange,提问作者The Outstanding Question Asker
相关产品推荐
相关产品推荐

