Angular 15中MatChipList无KeyManager时的芯片激活操作问题
Angular 15 中 MatChipList 激活芯片操作方案
在Angular 15中,MatChipList的_keyManager属性改为protected,无法直接访问,但可通过组件公开API或间接方式实现所需功能:
1. 确定当前激活的芯片
激活状态对应芯片的焦点状态,可通过芯片的hasFocus()方法判断:
getActiveChip(): MatChip | undefined { return this.list.chips.find(chip => chip.hasFocus()); }
2. 获取激活芯片的索引
基于激活芯片实例,通过数组indexOf方法获取索引:
getActiveChipIndex(): number { const activeChip = this.list.chips.find(chip => chip.hasFocus()); return activeChip ? this.list.chips.indexOf(activeChip) : -1; }
3. 将指定芯片设置为激活状态
直接调用目标芯片的focus()方法即可使其获得焦点(激活),若需同时选中芯片可搭配setSelected()方法:
// 将指定索引的芯片设为激活状态 setChipActive(index: number): void { const chips = this.list.chips.toArray(); if (index >= 0 && index < chips.length) { chips[index].focus(); // 可选:同时选中芯片 this.list.setSelected(chips[index]); } } // 原selectLastChip方法的替代实现 selectLastChip(): void { const chips = this.list.chips.toArray(); if (chips.length > 0) { chips[chips.length - 1].focus(); this.list.setSelected(chips[chips.length - 1]); } }
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

