Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable keyboard interaction of md-select in angular 4?

In Angular Material docs md-select has keyboard interaction: up arrow to select previous option, down arrow to select next option, space/enter to select option. I need to disable this keyboard interaction. Is there any way to disable it?

like image 574
aiswarya Avatar asked Sep 22 '17 09:09

aiswarya


3 Answers

In your md-option, add (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>

Link to working demo.

like image 143
Faisal Avatar answered Oct 22 '22 03:10

Faisal


For Angular-v7 and above: Use a input control so that we don't need to change built-in behavior of Angular Material Select, as @RyanDiehl suggested we should avoid.

Note: I'm adding this answer because I believe this sort of behavior will be required when someone wants to add a filter or to allow user to insert option into options. So I took the liberty to add this answer for other developers like myself, who have this situation.

In input, add (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>

Link to working demo.

GitHub Issue

like image 8
Muhammad Waqas Dilawar Avatar answered Oct 22 '22 04:10

Muhammad Waqas Dilawar


For library that built on top of Angular Material, you have to use (keydown)="$event.stopImmediatePropagation()". Here is a explanation of 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>
like image 1
luke Avatar answered Oct 22 '22 03:10

luke