首页 > 解决方案 > 如何使用 Angular 中的 Tab 键从 mat 下拉列表中选择一个选项

问题描述

我正在使用一个包含一些键和输入字段的下拉列表。

目前,当我选择下拉菜单并按 Tab 键时,它将转到第二个下拉菜单。

我期望的行为是,在选择下拉菜单并按下选项卡按钮后,它应该选择下拉菜单中的下一个项目。

下面是显示我期望的行为的图像

在此处输入图像描述

这是我的代码

<div class="fromTo">
   <mat-form-field style="width: 30%;">
      <mat-label>From</mat-label>
      <mat-select panelClass="fromSelect" style="margin-top:10% ;">
         <input matInput [(ngModel)]='searchValue' placeholder="Search" style="height: 35px; background-color: #f3f5f8; width: 98%;"/>
         <button mat-icon-button matSuffix (click)="onKeyAgency(searchValue)" class="cursor-pointer" type="button" style="float: right;position: absolute; right: 0;">
            <mat-icon class="search_icon">search</mat-icon>
         </button>
         <button mat-button (click)="showAdd=!showAdd" style="width: 100%;text-align: left;"><mat-icon>add</mat-icon>   Add New</button>
         <input matInput [ngClass]="{ 'hide':  showAdd}" [(ngModel)]='newPlace' placeholder="add" style="height: 35px; background-color: #f3f5f8; width: 98%;  position: inherit; "/>
         <button mat-icon-button matSuffix (click)="addPlace(newPlace)" [ngClass]="{ 'hide': showAdd }" class="cursor-pointer" type="button" style="float: right; position: absolute; right: 10%;">
            <mat-icon class="search_icon">done</mat-icon>
         </button>
         <button mat-icon-button matSuffix (click)="newPlace=''" [ngClass]="{ 'hide': showAdd }" class="cursor-pointer" type="button" style="float: right; position: absolute; right: 0;">
            <mat-icon class="search_icon">close</mat-icon>
         </button>
         <mat-option>None</mat-option>
         <mat-option *ngFor="let places of selectedAgencies" [value]="places">{{places}}</mat-option>
      </mat-select>
   </mat-form-field>
</div>

标签: javascripthtmlangularangular-material

解决方案


在您的模板中添加tabindex如下选项 -

 <div class="fromTo">
       <mat-form-field style="width: 30%;">
             <input (keydown)="onKeydown($event)" />
             <mat-option>None</mat-option>
              <!-- Add table index to matOptions-->
             <mat-option *ngFor="let places of selectedAgencies;let i = index" [value]="places" tabindex="index">{{places}}</mat-option>
          </mat-select>
       </mat-form-field>
    </div>

然后在您的组件中,将keydown输入字段中的事件绑定到组件中的回调。这应该避免面板关闭 -

onKeydown(event) {
  if (event.keyCode === 9) {
       event.stopPropagation();
    }
}

推荐阅读