Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Angular/material mat-menu from closing on key-navigation (tab)?

I have read How to prevent angular material mat-menu from closing? , which explains how to prevent Angular material mat-menu from closing on click.

However: I cannot seem to find a way to prevent a mat-menu from closing when I press tabulator to change focus.

Take this StackBlitz as an example: https://stackblitz.com/edit/angular-ij6jbx: it properly prevents the mat-menu from closing when the input-fields receive the focus via mouse click. On the other hand: if I press "tabulator" to change focus and the username-input-field receives the focus, the menu closes.

I would like to know how to prevent this behavior - if it's possible. I tried attaching $event.stopPropagation(); to (input), but it did not seem to do anything.

Apparently some thought has been given to this by the Angular developers according to https://github.com/angular/material2/issues/2612. Sadly there does not seem to be a proper solution at the end of the issue / feature-request nor a hint about the status.

P.s.: I know, that the current code is not beautiful nor really smart. I was going to refactor that into its own directive once it worked for both click and key-press.

like image 822
Igor Avatar asked Jun 03 '18 14:06

Igor


1 Answers

You can catch keydown event as follows:

<mat-menu ...>
  <form (keydown.tab)="$event.stopPropagation()">

Forked Stackblitz

Also, I would add tabindex="-1" to all clear buttons

like image 70
yurzui Avatar answered Nov 15 '22 23:11

yurzui