angular / angular/components

bug(cdkMenu): Menu closes unexpectedly after button is clicked and it is destroyed or made disabled

Open
#29,420 3 comments 1 reaction 0 assignees View on GitHub
area: cdk/menu P4
Dominant language
TypeScript
Stars
25k
Forks
6.8k
Avg merge
1d 8h
Merged PRs (30d)
91

Description

### Is this a regression?

- [ ] Yes, this behavior used to work in the previous version

### The previous version in which this bug was not present was

_No response_

### Description

My goal is to implement a button that opens a menu. On this menu there are static elements (texts) and some button.
When button is clicked then button is removed from the DOM (or disabled).

This cannot be implemented using `cdkMenuTriggerFor` and `cdkMenu` because cdkMenu is closed automatically.

### Reproduction

StackBlitz link: https://stackblitz.com/edit/pbb6fn
Steps to reproduce:
1. click on "Click me" to open the menu
2. click on "Refresh" item

PS:
Notice that buttons don't have `cdkMenuItem` directive applied on purpose.

### Expected Behavior

Have ability to stop closing of the menu when button is disabled or button is destroyed (removed from the DOM) after button click.

### Actual Behavior

Menu is closed due to lost focus on the clicked button (I guess).
Same problem occurs if on item click we destroy the button (e.g. using `ngIf="!btnDisabled"`)

### Environment

- Angular: 18.1.0
- CDK/Material: 18.1.0
- Browser(s): Google Chrome 126.0.6478.127
- Operating System (e.g. Windows, macOS, Ubuntu): Windows 11

Contributor guide

Open the contributing guide

Research direction

Start with the linked StackBlitz reproduction and trace the CDK menu focus behavior after the Refresh button is clicked. Verify the case where the button is disabled or removed from the DOM, then confirm that the menu remains open without applying cdkMenuItem to the button.

Written by the indexing model from the issue text.

Assessment

Tech stack
angular, typescript
Domain
frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.