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

angularangular-material

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.

Best Answer

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

Related Topic