Angular Material 使用向上和向下箭头键导航行
Angular Material Navigate rows using up and down arrow key
我向我的 mat-table 添加了自定义 ngclass
以使行可点击。但现在我希望用户能够使用向上和向下箭头键进行导航。使用此 git 集线器作为参考(https://github.com/angular/components/issues/14861) I was able to get it to work on the first try by using the tabindex
to capture the keydown event. But I have not been able to find out why it only works on the first try; Here is the stack blitz: https://stackblitz.com/edit/arrownavigation?file=app%2Ftable-basic-example.html
.HTML
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns; let i= index"
[ngClass]="{'highlight': selectedRowIndex == row.position}"
(click)="highlight(row, i)"
tabindex="999"
(keydown.arrowdown)="arrowDownEvent(row, i)"
(keydown.arrowup)="arrowUpEvent(row, i)"></tr>
</table>
.TS
highlight(row: any){
this.selectedRowIndex = row.position;
console.log(row);
}
arrowUpEvent(row: object, index: number){
var nextrow = this.dataSource[index - 1];
this.highlight(nextrow);
}
arrowDownEvent(row: object, index: number){
var nextrow = this.dataSource[index + 1];
this.highlight(nextrow);
console.log(index);
}
.CSS
.highlight{
background: yellow;
}
tr:focus{
outline: none;
}
我已经解决了问题,现在可以正常使用了。看到这个:
https://stackblitz.com/edit/arrownavigation-9qz7d5?file=app/table-basic-example.html
主要问题是,您在应该传递 selectedRowIndex.Then 的 arrowDownEvent 和 arrowUpEvent 中传递了 'i',您定义的数组是从 0 开始索引的,但索引 'i' *matRowDef 是 1 索引的。所以我不得不改变 arrowDownEvent 和 arrowUpEvent 中的一些逻辑来解决这个问题
我向我的 mat-table 添加了自定义 ngclass
以使行可点击。但现在我希望用户能够使用向上和向下箭头键进行导航。使用此 git 集线器作为参考(https://github.com/angular/components/issues/14861) I was able to get it to work on the first try by using the tabindex
to capture the keydown event. But I have not been able to find out why it only works on the first try; Here is the stack blitz: https://stackblitz.com/edit/arrownavigation?file=app%2Ftable-basic-example.html
.HTML
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns; let i= index"
[ngClass]="{'highlight': selectedRowIndex == row.position}"
(click)="highlight(row, i)"
tabindex="999"
(keydown.arrowdown)="arrowDownEvent(row, i)"
(keydown.arrowup)="arrowUpEvent(row, i)"></tr>
</table>
.TS
highlight(row: any){
this.selectedRowIndex = row.position;
console.log(row);
}
arrowUpEvent(row: object, index: number){
var nextrow = this.dataSource[index - 1];
this.highlight(nextrow);
}
arrowDownEvent(row: object, index: number){
var nextrow = this.dataSource[index + 1];
this.highlight(nextrow);
console.log(index);
}
.CSS
.highlight{
background: yellow;
}
tr:focus{
outline: none;
}
我已经解决了问题,现在可以正常使用了。看到这个:
https://stackblitz.com/edit/arrownavigation-9qz7d5?file=app/table-basic-example.html
主要问题是,您在应该传递 selectedRowIndex.Then 的 arrowDownEvent 和 arrowUpEvent 中传递了 'i',您定义的数组是从 0 开始索引的,但索引 'i' *matRowDef 是 1 索引的。所以我不得不改变 arrowDownEvent 和 arrowUpEvent 中的一些逻辑来解决这个问题