Angular7中Ng-Multiselect-Dropdown动态添加后无法更新求助
问题解决与组件推荐
一、修复现有Ng-Multiselect-Dropdown的更新失效问题
1. 移除表单绑定冲突
模板中同时使用[(ngModel)]和formControlName会导致Angular表单状态混乱,必须移除其中一个,推荐保留formControlName,通过表单控件管理选中值:
<ng-multiselect-dropdown [settings]="settings" name="cuisine" [placeholder]="'select '" [data]="Cusinesoptions" formControlName="cuisine" id="cuisineselected" (onSelect)="onItemSelect($event)" (onDeSelect)="onItemDeSelect($event)" style="margin-left: 20px; width: 50%;" ></ng-multiselect-dropdown>
2. 触发变更检测更新数据源
直接赋值数组可能无法触发Angular变更检测,需通过创建新数组的方式更新:
this.outletService.listCuisines().subscribe(response => { console.log("cuisine list", response); this.appspinner.spinnerAlert('hide'); // 用扩展运算符创建新数组,强制触发变更检测 this.Cusinesoptions = [...response.body['cusinies']]; });
3. 正确回显编辑状态的选中值
如果是编辑场景需要回显已选数据,需确保传入的选中值与settings中的idField匹配(当前idField为CuisinesName):
// 假设已选菜系名称数组为selectedCuisines this.yourFormGroup.get('cuisine').setValue(selectedCuisines);
二、适配Angular7的多功能多选下拉组件方案
1. 基于现有组件扩展增删改查功能
通过自定义逻辑在Ng-Multiselect-Dropdown基础上实现增删改查:
- 新增:在页面添加输入框和按钮,点击后将新选项推入
Cusinesoptions数组,同时更新表单选中值 - 删除:在
onItemDeSelect事件中同步移除数据源中对应项(若需要) - 编辑:双击已选项弹出输入框,修改后更新数据源中对应项的
CuisinesName
示例新增逻辑:
addNewCuisine(newName: string) { if (newName && !this.Cusinesoptions.some(item => item.CuisinesName === newName)) { this.Cusinesoptions = [...this.Cusinesoptions, { CuisinesName: newName }]; // 自动选中新增项 const currentSelected = this.yourFormGroup.get('cuisine').value || []; this.yourFormGroup.get('cuisine').setValue([...currentSelected, newName]); } }
2. 使用@ng-select/ng-select(兼容Angular7)
@ng-select/ng-select对Angular7支持良好,支持高度自定义模板,可快速实现增删改查:
<ng-select [items]="Cusinesoptions" bindLabel="CuisinesName" bindValue="CuisinesName" [multiple]="true" formControlName="cuisine"> <!-- 下拉底部添加新增输入框 --> <ng-template ng-footer-tmp> <input type="text" [(ngModel)]="newCuisine" placeholder="添加新菜系"> <button (click)="addNewCuisine()">确认添加</button> </ng-template> <!-- 已选项添加删除按钮 --> <ng-template ng-tag-tmp let-item="item" let-index="index"> <span>{{ item.CuisinesName }}</span> <button (click)="removeSelectedCuisine(index)" style="margin-left: 8px;">×</button> </ng-template> </ng-select>
对应组件逻辑:
newCuisine: string; addNewCuisine() { if (this.newCuisine && !this.Cusinesoptions.some(item => item.CuisinesName === this.newCuisine)) { this.Cusinesoptions = [...this.Cusinesoptions, { CuisinesName: this.newCuisine }]; const currentSelected = this.yourFormGroup.get('cuisine').value || []; this.yourFormGroup.get('cuisine').setValue([...currentSelected, this.newCuisine]); this.newCuisine = ''; } } removeSelectedCuisine(index: number) { const currentSelected = this.yourFormGroup.get('cuisine').value || []; currentSelected.splice(index, 1); this.yourFormGroup.get('cuisine').setValue([...currentSelected]); }
内容的提问来源于stack exchange,提问作者Suriya Rajasekar
相关产品推荐
相关产品推荐

