Skip to content

Commit 087ac4d

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 d5cd0d6 commit 087ac4d

File tree

7 files changed

+288
-56
lines changed

7 files changed

+288
-56
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: 62 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,20 @@ 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,
3230
NgZone,
3331
OnInit,
32+
QueryList,
33+
ContentChildren,
3434
} from '@angular/core';
3535
import {Observable} from 'rxjs';
3636
import {Subject} from 'rxjs';
@@ -39,11 +39,12 @@ import {Subscription} from 'rxjs';
3939
import {matMenuAnimations} from './menu-animations';
4040
import {throwMatMenuInvalidPositionX, throwMatMenuInvalidPositionY} from './menu-errors';
4141
import {MatMenuItem} from './menu-item';
42-
import {MatMenuPanel} from './menu-panel';
42+
import {MatMenuPanel, MAT_MENU_PANEL} from './menu-panel';
4343
import {MatMenuContent} from './menu-content';
4444
import {MenuPositionX, MenuPositionY} from './menu-positions';
4545
import {coerceBooleanProperty} from '@angular/cdk/coercion';
4646
import {FocusOrigin} from '@angular/cdk/a11y';
47+
import {AnimationEvent} from '@angular/animations';
4748

4849

4950
/** Default `mat-menu` options that can be overridden. */
@@ -90,18 +91,28 @@ const MAT_MENU_BASE_ELEVATION = 2;
9091
styleUrls: ['menu.css'],
9192
changeDetection: ChangeDetectionStrategy.OnPush,
9293
encapsulation: ViewEncapsulation.None,
94+
preserveWhitespaces: false,
95+
exportAs: 'matMenu',
9396
animations: [
9497
matMenuAnimations.transformMenu,
9598
matMenuAnimations.fadeInItems
9699
],
97-
exportAs: 'matMenu'
100+
providers: [
101+
{provide: MAT_MENU_PANEL, useExisting: MatMenu}
102+
]
98103
})
99-
export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestroy {
104+
export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel<MatMenuItem>, OnDestroy {
100105
private _keyManager: FocusKeyManager<MatMenuItem>;
101106
private _xPosition: MenuPositionX = this._defaultOptions.xPosition;
102107
private _yPosition: MenuPositionY = this._defaultOptions.yPosition;
103108
private _previousElevation: string;
104109

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

@@ -112,7 +123,10 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
112123
_panelAnimationState: 'void' | 'enter' = 'void';
113124

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

117131
/** Parent menu of the current menu panel. */
118132
parentMenu: MatMenuPanel | undefined;
@@ -148,7 +162,11 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
148162
/** @docs-private */
149163
@ViewChild(TemplateRef) templateRef: TemplateRef<any>;
150164

151-
/** List of the items inside of a menu. */
165+
/**
166+
* List of the items inside of a menu.
167+
* @deprecated
168+
* @deletion-target 7.0.0
169+
*/
152170
@ContentChildren(MatMenuItem) items: QueryList<MatMenuItem>;
153171

154172
/**
@@ -224,7 +242,7 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
224242
}
225243

226244
ngAfterContentInit() {
227-
this._keyManager = new FocusKeyManager<MatMenuItem>(this.items).withWrap().withTypeAhead();
245+
this._keyManager = new FocusKeyManager<MatMenuItem>(this._items).withWrap().withTypeAhead();
228246
this._tabSubscription = this._keyManager.tabOut.subscribe(() => this.close.emit('tab'));
229247
}
230248

@@ -235,16 +253,10 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
235253

236254
/** Stream that emits whenever the hovered menu item changes. */
237255
_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()));
256+
return this._itemChanges.pipe(
257+
startWith(this._items),
258+
switchMap(items => merge(...items.map(item => item._hovered)))
259+
);
248260
}
249261

250262
/** Handle a keyboard event from the menu, delegating to the appropriate action. */
@@ -322,6 +334,35 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
322334
}
323335
}
324336

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

337378
/** Callback that is invoked when the panel animation completes. */
338-
_onAnimationDone() {
339-
this._animationDone.next();
379+
_onAnimationDone(event: AnimationEvent) {
380+
this._animationDone.next(event);
381+
this._isAnimating = false;
340382
}
341383
}

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)