Ng-Select自定义文本移除后不加入下拉列表的解决方案求助
ng-select移除自定义标签后不加入下拉列表的解决方法
问题原因
ng-select默认会把通过addTag创建的自定义标签自动添加到items数据源数组中,所以移除标签后它会出现在下拉列表里。我们需要通过事件监听区分原生选项和自定义标签,阻止自定义标签进入下拉数据源。
具体解决步骤
- 给ng-select添加移除事件监听
修改HTML代码,加上(remove)事件捕获移除动作:
<ng-select [items]="companies" [addTag]="addTagFn" [hideSelected]="true" multiple="true" bindLabel="name" [(ngModel)]="selectedCompanies" (remove)="onRemove($event)" > </ng-select>
- 实现移除处理逻辑
在.ts文件中添加onRemove方法,判断被移除的是否是自定义标签(通过我们标记的tag: true),如果是,直接从选中列表中过滤掉,不允许它进入下拉数据源:
selectedCompanies; companies: any[] = []; companiesNames = ['Uber', 'Microsoft', 'Flexigen']; ngOnInit() { this.companiesNames.forEach((c, i) => { this.companies.push({ id: i, name: c }); }); } addTagFn(name) { // 给自定义标签加唯一标识+唯一ID,避免和原生选项冲突 return { id: Date.now(), name: name, tag: true }; } onRemove(event: any) { // 判断当前移除的是自定义标签 if (event.item.tag) { // 从选中数组中过滤掉该标签,阻止它被添加到下拉列表 this.selectedCompanies = this.selectedCompanies.filter(item => item !== event.item); } }
补充说明
- 给自定义标签加
id: Date.now()是为了避免和原生选项的id重复,防止识别混乱 - 这个方法属于轻量自定义逻辑,无需修改ng-select核心配置
内容的提问来源于stack exchange,提问作者Kamal Bansal
相关产品推荐
相关产品推荐

