Skip to content

feat(COMPONENT): Programmatically open/close menu #31993

@olfek

Description

@olfek

Feature Description

feat(COMPONENT): Programmatically open/close menu

When the menu is clicked, it opens right away.

I want to handle the click event and programmatically open the menu after doing another operation.

My workaround at present:

<button matButton (click)="listData(dataMenu, $event)" #dataMenuBtn>List Data</button>
<mat-menu #dataMenu>
    @for (item of data; track item)
    {
        <button mat-menu-item>{{ item.text }}</button>
    }
</mat-menu>
@ViewChild('dataMenuBtn', { read: ViewContainerRef })
private readonly dataMenuBtnViewContainerRef!: ViewContainerRef;

@ViewChild('dataMenuBtn', { read: ElementRef })
private readonly dataMenuBtnElementRef!: ElementRef;

private dataMenuTrigger!: MatMenuTrigger;
protected data: { text: string }[] = [];

protected async listData(dataMenu: MatMenu, $event: MouseEvent): Promise<void>
{
    const menuTrigger = this.dataMenuTrigger ?? (this.dataMenuTrigger = runInInjectionContext(Injector.create({
        providers: [
            {
                provide: ElementRef,
                useValue: this.dataMenuBtnElementRef
            },
            {
                provide: ViewContainerRef,
                useValue: this.dataMenuBtnViewContainerRef
            }
        ],
        parent: this.injector // `Injector` via DI.
    }), () => new MatMenuTrigger()));
    menuTrigger.menu = dataMenu;
    const result = await fetch(`/api/...`);
    this.data = await result.json() as typeof this.data;
    menuTrigger.openMenu();
}

Use Case

Load data inside menu on click

Metadata

Metadata

Assignees

No one assigned

    Labels

    P4A relatively minor issue that is not relevant to core functionsarea: material/menufeatureThis issue represents a new feature or feature request rather than a bug or bug fix

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions