Skip to content

feat(cdk/menu): add setActiveMenuItem to cdkMenu #31371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/cdk/menu/menu-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,20 @@ export abstract class CdkMenuBase
this.keyManager.setLastItemActive();
}

/**
* Sets the active item to the item at the specified index and focuses the newly active item.
* @param item The index of the item to be set as active, or the CdkMenuItem instance.
*/
setActiveMenuItem(item: number | CdkMenuItem) {
if (this.keyManager) {
if (typeof item === 'number') {
this.keyManager.setActiveItem(item);
} else {
this.keyManager.setActiveItem(item);
}
}
}

/** Gets the tabindex for this menu. */
_getTabIndex() {
return this._tabIndexSignal();
Expand Down
42 changes: 42 additions & 0 deletions src/cdk/menu/menu.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,33 @@ describe('Menu', () => {
}));
});
});

describe('menu with active item', () => {
let fixture: ComponentFixture<MenuWithActiveItem>;
let nativeMenu: HTMLElement;
let nativeMenuItems: HTMLElement[];

beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule, MenuWithActiveItem],
});
}));

beforeEach(() => {
fixture = TestBed.createComponent(MenuWithActiveItem);
fixture.detectChanges();

nativeMenu = fixture.debugElement.query(By.directive(CdkMenu)).nativeElement;
nativeMenuItems = fixture.debugElement
.queryAll(By.directive(CdkMenuItem))
.map(e => e.nativeElement);
});

it('should set the active item with setActiveMenuItem', () => {
fixture.componentInstance.menu.setActiveMenuItem(2);
expect(document.activeElement).toEqual(nativeMenuItems[2]);
});
});
});

@Component({
Expand Down Expand Up @@ -655,3 +682,18 @@ class WithComplexNestedMenusOnBottom {

@ViewChildren(CdkMenu) menus: QueryList<CdkMenu>;
}

@Component({
template: `
<div cdkMenu>
<button cdkMenuItem>Inbox</button>
<button cdkMenuItem>Starred</button>
<button cdkMenuItem>Foo</button>
<button cdkMenuItem>Bar</button>
</div>
`,
imports: [CdkMenuModule],
})
class MenuWithActiveItem {
@ViewChild(CdkMenu) menu: CdkMenu;
}