Reputation: 136
Hey guys I do have a simple <mat-select>
form where users could choose between three options. If the user has selected an option and presses the enter key the search button should be triggered. So far everything works fine with that code below:
<mat-input-container>
<mat-select onkeydown="if (event.keyCode == 13)
document.getElementById('btnSearch').click();>
<mat-option>
Option 1
</mat-option>
<mat-option>
Option 2
</mat-option>
<mat-option>
Option 3
</mat-option>
</mat-select>
</mat-input-container>
<button mat-button id="btnSearch" (click)="search()">Search</button>
Now here is my problem:
If the user has chosen one option and presses the enter key the <mat-select>
form expands and all options are shown again. Is there a way to disable this behaviour?
I tried to add something like $event.stopPropagation();
to the onkeydown event but it didn´t work out.
I found pretty similar question here Is there a way to change this Angular 4+ Material Design Mat-Select default behavior? But It didn´t solve my problem
Anybody who could help? Best regards
Upvotes: 1
Views: 1999
Reputation: 49
You can use this to prevent expanding of drop-down option on Enter-Key press once it is selected. I was having same issue and i fixed this using below code in mat-select
.
<mat-select
(keydown.enter)="$event.stopImmediatePropagation();" >
With reference to your code instead of using
onkeydown="if (event.keyCode == 13)
document.getElementById('btnSearch').click(); this in `mat-select`.
Use as below code.
<mat-input-container>
<mat-select (keydown.enter)="$event.stopImmediatePropagation();">
<mat-option>
Option 1
</mat-option>
<mat-option>
Option 2
</mat-option>
<mat-option>
Option 3
</mat-option>
</mat-select>
</mat-input-container>
<button mat-button id="btnSearch" (click)="search()">Search</button>
Upvotes: 0
Reputation:
Hints for starters : you can replace this
<mat-select
onkeydown="if (event.keyCode == 13) document.getElementById('btnSearch').click();>
With this :
<mat-select (keyup.enter)="document.getElementById('btnSearch').click();>
This is how you detect an enter key in Angular.
Furtermore, since you are using Angular, you have access to local variables. this means you can (but more importantly, you should) do this :
<mat-select (keyup.enter)="search.click();>
<button #search mat-button id="btnSearch" (click)="search()">Search</button>
Now, about your issue, I also faced it and never have been able to resolve it. What you should do, however, is open an issue on their Github repository, and ask for a way to prevent the options expansion.
Upvotes: 1