Skip to content

Commit dd5c23c

Browse files
committed
fix(menu): unable to open same sub-menu from different triggers and not picking up indirect descendant items
* Reworks the relationship between the menu items and the menu panel to allow for the items to be indirect descendants of the menu, while also allowing for `mat-menu` instances to be declared inside of other `mat-menu` instances without having the root `mat-menu` pick up all of the descendant items. * Adds the ability to pass in an array to the `ListKeyManager`, in addition to a `QueryList`. * Fixes not being able to re-use the same sub-menu between multiple sub-menu triggers. Fixes #9969. Fixes #9987.
1 parent 0e37d6c commit dd5c23c

File tree

7 files changed

+283
-58
lines changed

7 files changed

+283
-58
lines changed

src/cdk/a11y/key-manager/list-key-manager.ts

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -52,17 +52,22 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
5252
// Buffer for the letters that the user has pressed when the typeahead option is turned on.
5353
private _pressedLetters: string[] = [];
5454

55-
constructor(private _items: QueryList<T>) {
56-
_items.changes.subscribe((newItems: QueryList<T>) => {
57-
if (this._activeItem) {
58-
const itemArray = newItems.toArray();
59-
const newIndex = itemArray.indexOf(this._activeItem);
60-
61-
if (newIndex > -1 && newIndex !== this._activeItemIndex) {
62-
this._activeItemIndex = newIndex;
55+
constructor(private _items: QueryList<T> | T[]) {
56+
// We allow for the items to be an array because, in some cases, the consumer may
57+
// not have access to a QueryList of the items they want to manage (e.g. when the
58+
// items aren't being collected via `ViewChildren` or `ContentChildren`).
59+
if (_items instanceof QueryList) {
60+
_items.changes.subscribe((newItems: QueryList<T>) => {
61+
if (this._activeItem) {
62+
const itemArray = newItems.toArray();
63+
const newIndex = itemArray.indexOf(this._activeItem);
64+
65+
if (newIndex > -1 && newIndex !== this._activeItemIndex) {
66+
this._activeItemIndex = newIndex;
67+
}
6368
}
64-
}
65-
});
69+
});
70+
}
6671
}
6772

6873
/**
@@ -132,7 +137,7 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
132137
filter(() => this._pressedLetters.length > 0),
133138
map(() => this._pressedLetters.join(''))
134139
).subscribe(inputString => {
135-
const items = this._items.toArray();
140+
const items = this._getItemsArray();
136141

137142
// Start at 1 because we want to start searching at the item immediately
138143
// following the current active item.
@@ -288,7 +293,7 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
288293
updateActiveItem(item: T): void;
289294

290295
updateActiveItem(item: any): void {
291-
const itemArray = this._items.toArray();
296+
const itemArray = this._getItemsArray();
292297
const index = typeof item === 'number' ? item : itemArray.indexOf(item);
293298

294299
this._activeItemIndex = index;
@@ -310,17 +315,18 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
310315
* currently active item and the new active item. It will calculate differently
311316
* depending on whether wrap mode is turned on.
312317
*/
313-
private _setActiveItemByDelta(delta: -1 | 1, items = this._items.toArray()): void {
314-
this._wrap ? this._setActiveInWrapMode(delta, items)
315-
: this._setActiveInDefaultMode(delta, items);
318+
private _setActiveItemByDelta(delta: -1 | 1): void {
319+
this._wrap ? this._setActiveInWrapMode(delta) : this._setActiveInDefaultMode(delta);
316320
}
317321

318322
/**
319323
* Sets the active item properly given "wrap" mode. In other words, it will continue to move
320324
* down the list until it finds an item that is not disabled, and it will wrap if it
321325
* encounters either end of the list.
322326
*/
323-
private _setActiveInWrapMode(delta: -1 | 1, items: T[]): void {
327+
private _setActiveInWrapMode(delta: -1 | 1): void {
328+
const items = this._getItemsArray();
329+
324330
for (let i = 1; i <= items.length; i++) {
325331
const index = (this._activeItemIndex + (delta * i) + items.length) % items.length;
326332
const item = items[index];
@@ -337,17 +343,18 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
337343
* continue to move down the list until it finds an item that is not disabled. If
338344
* it encounters either end of the list, it will stop and not wrap.
339345
*/
340-
private _setActiveInDefaultMode(delta: -1 | 1, items: T[]): void {
341-
this._setActiveItemByIndex(this._activeItemIndex + delta, delta, items);
346+
private _setActiveInDefaultMode(delta: -1 | 1): void {
347+
this._setActiveItemByIndex(this._activeItemIndex + delta, delta);
342348
}
343349

344350
/**
345351
* Sets the active item to the first enabled item starting at the index specified. If the
346352
* item is disabled, it will move in the fallbackDelta direction until it either
347353
* finds an enabled item or encounters the end of the list.
348354
*/
349-
private _setActiveItemByIndex(index: number, fallbackDelta: -1 | 1,
350-
items = this._items.toArray()): void {
355+
private _setActiveItemByIndex(index: number, fallbackDelta: -1 | 1): void {
356+
const items = this._getItemsArray();
357+
351358
if (!items[index]) {
352359
return;
353360
}
@@ -362,4 +369,9 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
362369

363370
this.setActiveItem(index);
364371
}
372+
373+
/** Returns the items as an array. */
374+
private _getItemsArray(): T[] {
375+
return this._items instanceof QueryList ? this._items.toArray() : this._items;
376+
}
365377
}

src/lib/menu/menu-directive.ts

Lines changed: 55 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,13 @@ import {
1717
ChangeDetectionStrategy,
1818
Component,
1919
ContentChild,
20-
ContentChildren,
2120
ElementRef,
2221
EventEmitter,
2322
Inject,
2423
InjectionToken,
2524
Input,
2625
OnDestroy,
2726
Output,
28-
QueryList,
2927
TemplateRef,
3028
ViewChild,
3129
ViewEncapsulation,
@@ -39,11 +37,12 @@ import {Subscription} from 'rxjs';
3937
import {matMenuAnimations} from './menu-animations';
4038
import {throwMatMenuInvalidPositionX, throwMatMenuInvalidPositionY} from './menu-errors';
4139
import {MatMenuItem} from './menu-item';
42-
import {MatMenuPanel} from './menu-panel';
40+
import {MatMenuPanel, MAT_MENU_PANEL} from './menu-panel';
4341
import {MatMenuContent} from './menu-content';
4442
import {MenuPositionX, MenuPositionY} from './menu-positions';
4543
import {coerceBooleanProperty} from '@angular/cdk/coercion';
4644
import {FocusOrigin} from '@angular/cdk/a11y';
45+
import {AnimationEvent} from '@angular/animations';
4746

4847

4948
/** Default `mat-menu` options that can be overridden. */
@@ -90,18 +89,28 @@ const MAT_MENU_BASE_ELEVATION = 2;
9089
styleUrls: ['menu.css'],
9190
changeDetection: ChangeDetectionStrategy.OnPush,
9291
encapsulation: ViewEncapsulation.None,
92+
preserveWhitespaces: false,
93+
exportAs: 'matMenu',
9394
animations: [
9495
matMenuAnimations.transformMenu,
9596
matMenuAnimations.fadeInItems
9697
],
97-
exportAs: 'matMenu'
98+
providers: [
99+
{provide: MAT_MENU_PANEL, useExisting: MatMenu}
100+
]
98101
})
99-
export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestroy {
102+
export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel<MatMenuItem>, OnDestroy {
100103
private _keyManager: FocusKeyManager<MatMenuItem>;
101104
private _xPosition: MenuPositionX = this._defaultOptions.xPosition;
102105
private _yPosition: MenuPositionY = this._defaultOptions.yPosition;
103106
private _previousElevation: string;
104107

108+
/** Menu items inside the current menu. */
109+
private _items: MatMenuItem[] = [];
110+
111+
/** Emits whenever the amount of menu items changes. */
112+
private _itemChanges = new Subject<MatMenuItem[]>();
113+
105114
/** Subscription to tab events on the menu panel */
106115
private _tabSubscription = Subscription.EMPTY;
107116

@@ -112,7 +121,10 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
112121
_panelAnimationState: 'void' | 'enter' = 'void';
113122

114123
/** Emits whenever an animation on the menu completes. */
115-
_animationDone = new Subject<void>();
124+
_animationDone = new Subject<AnimationEvent>();
125+
126+
/** Whether the menu is animating. */
127+
_isAnimating: boolean;
116128

117129
/** Parent menu of the current menu panel. */
118130
parentMenu: MatMenuPanel | undefined;
@@ -148,9 +160,6 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
148160
/** @docs-private */
149161
@ViewChild(TemplateRef) templateRef: TemplateRef<any>;
150162

151-
/** List of the items inside of a menu. */
152-
@ContentChildren(MatMenuItem) items: QueryList<MatMenuItem>;
153-
154163
/**
155164
* Menu content that will be rendered lazily.
156165
* @docs-private
@@ -224,7 +233,7 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
224233
}
225234

226235
ngAfterContentInit() {
227-
this._keyManager = new FocusKeyManager<MatMenuItem>(this.items).withWrap().withTypeAhead();
236+
this._keyManager = new FocusKeyManager<MatMenuItem>(this._items).withWrap().withTypeAhead();
228237
this._tabSubscription = this._keyManager.tabOut.subscribe(() => this.close.emit('tab'));
229238
}
230239

@@ -235,16 +244,10 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
235244

236245
/** Stream that emits whenever the hovered menu item changes. */
237246
_hovered(): Observable<MatMenuItem> {
238-
if (this.items) {
239-
return this.items.changes.pipe(
240-
startWith(this.items),
241-
switchMap(items => merge(...items.map(item => item._hovered)))
242-
);
243-
}
244-
245-
return this._ngZone.onStable
246-
.asObservable()
247-
.pipe(take(1), switchMap(() => this._hovered()));
247+
return this._itemChanges.pipe(
248+
startWith(this._items),
249+
switchMap(items => merge(...items.map(item => item._hovered)))
250+
);
248251
}
249252

250253
/** Handle a keyboard event from the menu, delegating to the appropriate action. */
@@ -322,6 +325,35 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
322325
}
323326
}
324327

328+
/**
329+
* Registers a menu item with the menu.
330+
* @docs-private
331+
*/
332+
addItem(item: MatMenuItem) {
333+
// We register the items through this method, rather than picking them up through
334+
// `ContentChildren`, because we need the items to be picked up by their closest
335+
// `mat-menu` ancestor. If we used `@ContentChildren(MatMenuItem, {descendants: true})`,
336+
// all descendant items will bleed into the top-level menu in the case where the consumer
337+
// has `mat-menu` instances nested inside each other.
338+
if (this._items.indexOf(item) === -1) {
339+
this._items.push(item);
340+
this._itemChanges.next(this._items);
341+
}
342+
}
343+
344+
/**
345+
* Removes an item from the menu.
346+
* @docs-private
347+
*/
348+
removeItem(item: MatMenuItem) {
349+
const index = this._items.indexOf(item);
350+
351+
if (this._items.indexOf(item) > -1) {
352+
this._items.splice(index, 1);
353+
this._itemChanges.next(this._items);
354+
}
355+
}
356+
325357
/** Starts the enter animation. */
326358
_startAnimation() {
327359
// @deletion-target 6.0.0 Combine with _resetAnimation.
@@ -335,7 +367,8 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
335367
}
336368

337369
/** Callback that is invoked when the panel animation completes. */
338-
_onAnimationDone() {
339-
this._animationDone.next();
370+
_onAnimationDone(event: AnimationEvent) {
371+
this._animationDone.next(event);
372+
this._isAnimating = false;
340373
}
341374
}

src/lib/menu/menu-item.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
OnDestroy,
1515
ViewEncapsulation,
1616
Inject,
17+
Optional,
1718
} from '@angular/core';
1819
import {
1920
CanDisable,
@@ -23,6 +24,7 @@ import {
2324
} from '@angular/material/core';
2425
import {Subject} from 'rxjs';
2526
import {DOCUMENT} from '@angular/common';
27+
import {MAT_MENU_PANEL, MatMenuPanel} from './menu-panel';
2628

2729
// Boilerplate for applying mixins to MatMenuItem.
2830
/** @docs-private */
@@ -70,7 +72,8 @@ export class MatMenuItem extends _MatMenuItemMixinBase
7072
constructor(
7173
private _elementRef: ElementRef,
7274
@Inject(DOCUMENT) document?: any,
73-
private _focusMonitor?: FocusMonitor) {
75+
private _focusMonitor?: FocusMonitor,
76+
@Inject(MAT_MENU_PANEL) @Optional() private _parentMenu?: MatMenuPanel<MatMenuItem>) {
7477

7578
// @deletion-target 6.0.0 make `_focusMonitor` and `document` required params.
7679
super();
@@ -82,6 +85,10 @@ export class MatMenuItem extends _MatMenuItemMixinBase
8285
_focusMonitor.monitor(this._getHostElement(), false);
8386
}
8487

88+
if (_parentMenu && _parentMenu.addItem) {
89+
_parentMenu.addItem(this);
90+
}
91+
8592
this._document = document;
8693
}
8794

@@ -99,6 +106,10 @@ export class MatMenuItem extends _MatMenuItemMixinBase
99106
this._focusMonitor.stopMonitoring(this._getHostElement());
100107
}
101108

109+
if (this._parentMenu && this._parentMenu.removeItem) {
110+
this._parentMenu.removeItem(this);
111+
}
112+
102113
this._hovered.complete();
103114
}
104115

src/lib/menu/menu-panel.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,23 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import {EventEmitter, TemplateRef} from '@angular/core';
9+
import {EventEmitter, TemplateRef, InjectionToken} from '@angular/core';
1010
import {MenuPositionX, MenuPositionY} from './menu-positions';
1111
import {Direction} from '@angular/cdk/bidi';
1212
import {FocusOrigin} from '@angular/cdk/a11y';
1313
import {MatMenuContent} from './menu-content';
1414

15+
/**
16+
* Injection token used to provide the parent menu to menu-specific components.
17+
* @docs-private
18+
*/
19+
export const MAT_MENU_PANEL = new InjectionToken<MatMenuPanel>('MAT_MENU_PANEL');
20+
1521
/**
1622
* Interface for a custom menu panel that can be used with `matMenuTriggerFor`.
1723
* @docs-private
1824
*/
19-
export interface MatMenuPanel {
25+
export interface MatMenuPanel<T = any> {
2026
xPosition: MenuPositionX;
2127
yPosition: MenuPositionY;
2228
overlapTrigger: boolean;
@@ -31,4 +37,6 @@ export interface MatMenuPanel {
3137
lazyContent?: MatMenuContent;
3238
backdropClass?: string;
3339
hasBackdrop?: boolean;
40+
addItem?: (item: T) => void;
41+
removeItem?: (item: T) => void;
3442
}

0 commit comments

Comments
 (0)