如何在角4中禁用md-select的键盘交互?

时间:2017-09-22 09:36:40

标签: angular angular-material2

在Angular Material docs中,md-select具有键盘交互:向上箭头选择上一个选项,向下箭头选择下一个选项,空格/输入选择选项。我需要禁用此键盘交互。有没有办法禁用它?

3 个答案:

答案 0 :(得分:6)

md-option中,添加(keydown)="$event.stopPropagation()"

<md-select placeholder="Favorite food" >
  <md-option *ngFor="let food of foods" [value]="food.value" 
             (keydown)="$event.stopPropagation()" >
    {{ food.viewValue }}
  </md-option>
</md-select>

链接到working demo

答案 1 :(得分:0)

对于Angular-v7及更高版本: 使用输入控件,这样我们就不必更改 Angular Material Select 的内置行为,就像@RyanDiehl建议我们避免的那样。

注意:我之所以添加此答案,是因为我相信当某人想要添加过滤器或允许用户将选项插入选项时,将需要这种行为。因此,我很乐意为其他像我这样的开发人员添加这个答案。

input中,添加(keydown)="$event.stopPropagation()"

    <mat-form-field>
  <mat-select placeholder="Favorite food" multiple>
    <mat-form-field class="example-form-field">
      <input matInput type="text" placeholder="Clearable input" [(ngModel)]="value"
      (keydown)="$event.stopPropagation()">
      <button mat-button *ngIf="value" matSuffix mat-icon-button aria-label="Clear" (click)="save()">
        <mat-icon>done</mat-icon>
      </button>
    </mat-form-field>
    <mat-divider></mat-divider>
    <mat-option *ngFor="let food of foods" [value]="food.value" >
      {{food.viewValue}} <span> <button mat-button matSuffix mat-icon-button aria-label="Clear"
          (click)="delete(food.value)"
           >
          <mat-icon>close</mat-icon>
        </button></span>
    </mat-option>
  </mat-select>
</mat-form-field>

链接到working demo

GitHub Issue

答案 2 :(得分:0)

对于在Angular Material之上构建的库,您必须使用(keydown)="$event.stopImmediatePropagation()"。这是stopPropagation vs. stopImmediatePropagation的说明。

<custom-mat-select (keydown)="$event.stopImmediatePropagation()" multiple placeholder="Select ..." [(ngModel)]="selectedItems">
    <custom-mat-option *ngFor="let item of items" [value]="item.id">
        {{ item.name }}
    </custom-mat-option>
</custom-mat-select>