Search code examples
angularkeydownangular-material-table

arrowdown & arrowup key is not working using mat-table in angular


I share my code here when I press downarrow key firsttime it will go on next row but again I press downarrow it will not work properly (https://i.sstatic.net/4qznx.jpg)

**HTML**
<mat-row *matRowDef="let row; columns: displayedColumns; let index = 'index+1';" 
         class="table-row" 
         (click)="getRecordFromTable(row, index)" 
         tabindex="999" 
         (keydown.arrowdown)="arrowUpDownEvent(index,true)"
         (keydown.arrowup)="arrowUpDownEvent(index,false)" 
         (keydown.enter)="onConfirmButton(row,index)" 
         [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>

**TS**
arrowUpDownEvent(index: number,isDownArrow : boolean) { 
if (isDownArrow){ 
     let nextrow = this.customerFilterDataSource.data[index]; 
if (nextrow){ 
     this.getRecordFromTable(nextrow, index + 1);
 } 
}
else{ 
   let nextrow = this.customerFilterDataSource.data[index-2]; 
   if(nextrow){ 
        this.getRecordFromTable(nextrow, index - 2);
 } 
} 
} 

Solution

  • // Define a variable to keep track of the currently focused row index
    focusedRowIndex: number = -1;
    
    arrowUpDownEvent(index: number, isDownArrow: boolean) {
      if (isDownArrow) {
        // Move focus to the next row if available
        if (index < this.customerFilterDataSource.data.length - 1) {
          this.focusedRowIndex = index + 1;
        }
      } else {
        // Move focus to the previous row if available
        if (index > 0) {
          this.focusedRowIndex = index - 1;
        }
      }
    }
    
    // In your HTML template, bind the focusedRowIndex to each row's tabindex and classes
    <mat-row *matRowDef="let row; columns: displayedColumns; let index = index;"
             class="table-row"
             (click)="getRecordFromTable(row, index)"
             [tabindex]="focusedRowIndex === index ? '999' : null"
             (keydown.arrowdown)="arrowUpDownEvent(index, true)"
             (keydown.arrowup)="arrowUpDownEvent(index, false)"
             (keydown.enter)="onConfirmButton(row, index)"
             [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,
               'focused-row': focusedRowIndex === index
             }">
    </mat-row>