Angular中mat-table上下方向键功能异常问题排查
Angular mat-table 上下方向键失效问题修复
问题分析
从代码来看,方向键首次有效、后续失效的核心问题有三点:
- HTML中
*matRowDef的索引绑定错误:let index = 'index+1'是把字符串'index+1'赋值给变量,而非计算后的有效索引值,导致TS中拿到的索引逻辑混乱。 - 选中新行后未转移焦点:后续按键仍触发原行的
keydown事件,无法正确切换到目标行。 - TS中索引计算逻辑错误:向下键取
data[index]、向上键取data[index-2]的逻辑完全不符合数组下标(从0开始)的规则,容易出现越界或定位错误。
修复步骤
1. 修正HTML中的索引绑定与行标识
调整索引绑定逻辑,给mat-row添加可定位的属性,方便后续设置焦点:
<mat-row *matRowDef="let row; columns: displayedColumns; let originalIndex = index;" class="table-row" (click)="getRecordFromTable(row, originalIndex + 1)" tabindex="999" [attr.data-index]="originalIndex" (keydown.arrowdown)="arrowUpDownEvent(originalIndex, true)" (keydown.arrowup)="arrowUpDownEvent(originalIndex, false)" (keydown.enter)="onConfirmButton(row, originalIndex + 1)" [ngClass]="{ 'previous-highlighted': this._POSFormService.POSHeaderForm.get('walkInCustomerCode')?.value == row.code, 'current-highlighted': this.customerFormService.selectedCustomerCode.value == row.code && this._POSFormService.POSHeaderForm.get('walkInCustomerCode')?.value !== row.code }"> </mat-row>
这里用originalIndex获取表格原生的0起始索引,显示用的索引在调用方法时加1,同时通过data-index属性标记行的位置。
2. 修正TS中的方向键逻辑并添加焦点转移
arrowUpDownEvent(currentIndex: number, isDownArrow: boolean) { let targetIndex: number; const dataLength = this.customerFilterDataSource.data.length; if (isDownArrow) { // 向下切换:目标索引为当前索引+1,不超过数组最大下标 targetIndex = currentIndex + 1; if (targetIndex >= dataLength) return; } else { // 向上切换:目标索引为当前索引-1,不小于0 targetIndex = currentIndex - 1; if (targetIndex < 0) return; } const targetRow = this.customerFilterDataSource.data[targetIndex]; if (targetRow) { this.getRecordFromTable(targetRow, targetIndex + 1); // 切换后将焦点移到目标行 this.focusRow(targetIndex); } } // 新增焦点设置方法 private focusRow(index: number) { const rowElement = document.querySelector(`mat-row[data-index="${index}"]`) as HTMLElement; if (rowElement) { rowElement.focus(); } }
关键说明
- 基于数组原生的0起始索引计算目标行,彻底避免索引越界或定位错误。
- 每次切换行后强制转移焦点,确保后续按键事件触发在正确的行上。
- 移除原代码中错误的字符串索引绑定,保证索引值的有效性。
内容的提问来源于stack exchange,提问作者Miloni Shah
相关产品推荐
相关产品推荐

