Skip to content

help(matMenu): Auto focusing text box after clicking on a menu item #18750

@chenxinyanc

Description

@chenxinyanc

What are you trying to do?

  • I tried to move focus to a text box after user clicks the menu. This text box submits user input when it loses focus.
  • I want to know what is the correct / recommended approach to move focus to other control, we I'm inside a menu item click callback.
  • Is it possible for matMenu to stop moving focus to the triggering button when closing the menu, if user's focus is not inside matMenu at the time just before the menu closes? (something like Option for menu not to return focus to the assoicated button #11696, but with a pre-condition)

What troubleshooting steps have you tried?

I need to use setTimeout(..., 0) to defer moving focus to text box, so the focus will be moved to the menu-triggering button, then moved to the text box at last. However, this looks flaky to me and I'm not sure if it's the best practice.

Reproduction

https://stackblitz.com/edit/angular-component-mat-menu-focus?file=src%2Fapp%2Ftext-editor%2Ftext-editor.component.ts

Steps to reproduce:

  1. Open the sandbox link above, note the following code in text-editor.component.ts.
  ngAfterViewInit() {
    // If we remove setTimeout, textInput.blur event will be triggered immediately.
    window.setTimeout(() => {
      // Move focus to the text box automatically.
      this.textInput.nativeElement.focus();
    }, 0);
  }
  1. In the app, you can edit the text with "Edit" menu item. That's expected behavior.
    temp

  2. Remove setTimeout, calling focus directly instead

  ngAfterViewInit() {
    // Move focus to the text box automatically.
    this.textInput.nativeElement.focus();
  }
  1. In the app, the text box seems to get focus first, then lost focus almost immediately.
    temp

Environment

  • Angular: 9.0.2
  • CDK/Material: 9.1.0
  • Browser(s): Chrome 80.0.3987.132
  • Operating System (e.g. Windows, macOS, Ubuntu): Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    troubleshootingThis issue is not reporting an issue, but just asking for help

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions