Angular中MatChipGrid实现右键循环聚焦首个Chip的方法
实现MatChipGrid箭头循环聚焦(最后一个Chip按右箭头跳转到第一个)
在Angular 15/16中,MatChipGrid默认的箭头导航到首尾后就会停止,要实现循环聚焦,只需要拦截右箭头的键盘事件,在特定条件下手动切换焦点:
步骤1:修改模板绑定键盘事件
给mat-chip-grid添加keydown事件监听,捕获箭头按键操作:
<mat-chip-grid #list (keydown)="handleChipKeydown($event)"> <mat-chip-row *ngFor="let chip of chips"> {{chip}} </mat-chip-row> </mat-chip-grid>
步骤2:实现事件处理逻辑
在组件类中通过@ViewChild获取MatChipList实例,编写键盘事件处理函数:
import { Component, ViewChild } from '@angular/core'; import { MatChipList } from '@angular/material/chips'; @Component({ // 组件元数据(如selector、templateUrl等)按实际需求填写 }) export class YourComponent { chips = ['标签1', '标签2', '标签3']; // 示例数据,替换为你的实际数据 @ViewChild('list') list!: MatChipList; handleChipKeydown(event: KeyboardEvent): void { // 仅处理右箭头按键 if (event.key !== 'ArrowRight') return; const totalChips = this.list.chips.length; const focusedIndex = this.list.getFocusedChipIndex(); // 判断是否聚焦在最后一个Chip if (focusedIndex === totalChips - 1) { // 阻止默认导航行为(避免停在最后一个无响应) event.preventDefault(); // 手动聚焦第一个Chip this.list.focusFirstChip(); } } }
补充扩展
如果需要实现左箭头从第一个跳转到最后一个的循环逻辑,只需在处理函数中增加ArrowLeft的判断:
handleChipKeydown(event: KeyboardEvent): void { if (event.key === 'ArrowRight') { const totalChips = this.list.chips.length; const focusedIndex = this.list.getFocusedChipIndex(); if (focusedIndex === totalChips - 1) { event.preventDefault(); this.list.focusFirstChip(); } } else if (event.key === 'ArrowLeft') { const focusedIndex = this.list.getFocusedChipIndex(); if (focusedIndex === 0) { event.preventDefault(); this.list.focusLastChip(); } } }
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

