You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:07:14