Angular mat-select多选:代码设置取消选中项无效问题求助
解决Angular mat-select多选组件setValue后界面不更新的问题
问题核心在于你直接修改了原数组的引用:splice方法会修改原数组本身,而Angular的FormControl依赖数组的引用变化来触发视图更新。因为你传递给setValue的还是原来的数组引用,控件检测不到数据变更,所以界面选中状态不会更新。
修复方案(推荐):创建新数组传递给setValue
不要直接修改原数组,而是生成一个新的数组实例,这样FormControl能识别到数据变化并更新视图。有两种常用方式:
- 使用
filter直接过滤掉要移除的ID:
deletedRole(who: string) { const lstRolesControl = this.form.get('_lstRoles'); if (lstRolesControl) { this.obsTipiPersona$.pipe(take(1)).subscribe(options => { const roleToDeflag = options.find(option => option.descrizione === who); if (roleToDeflag) { const selectedRolesArray = lstRolesControl.value as number[]; // 生成新数组,过滤掉目标ID const updatedRoles = selectedRolesArray.filter(id => id !== roleToDeflag.id); lstRolesControl.setValue(updatedRoles); } }); } }
- 复制原数组后再修改(适合需要操作索引的场景):
deletedRole(who: string) { const lstRolesControl = this.form.get('_lstRoles'); if (lstRolesControl) { this.obsTipiPersona$.pipe(take(1)).subscribe(options => { const roleToDeflag = options.find(option => option.descrizione === who); if (roleToDeflag) { const selectedRolesArray = lstRolesControl.value as number[]; const indexToRemove = selectedRolesArray.findIndex(roleId => roleId === roleToDeflag.id); if (indexToRemove !== -1) { // 用扩展运算符复制原数组,生成新引用 const updatedRoles = [...selectedRolesArray]; updatedRoles.splice(indexToRemove, 1); lstRolesControl.setValue(updatedRoles); } } }); } }
为什么原代码添加选中项有效?
添加项时你大概率是创建了新数组(比如用concat或扩展运算符生成新数组后赋值),此时数组引用变化,FormControl能检测到并更新视图;而删除时用splice修改原数组,引用未变,所以没触发更新。
内容的提问来源于stack exchange,提问作者Nicola
相关产品推荐
相关产品推荐

