Skip to content

Commit d798784

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 a943b36 commit d798784

File tree

7 files changed

+283
-57
lines changed

7 files changed

+283
-57
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
@@ -56,17 +56,22 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
5656
// Buffer for the letters that the user has pressed when the typeahead option is turned on.
5757
private _pressedLetters: string[] = [];
5858

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

7277
/**
@@ -136,7 +141,7 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
136141
filter(() => this._pressedLetters.length > 0),
137142
map(() => this._pressedLetters.join(''))
138143
).subscribe(inputString => {
139-
const items = this._items.toArray();
144+
const items = this._getItemsArray();
140145

141146
// Start at 1 because we want to start searching at the item immediately
142147
// following the current active item.
@@ -292,7 +297,7 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
292297
updateActiveItem(item: T): void;
293298

294299
updateActiveItem(item: any): void {
295-
const itemArray = this._items.toArray();
300+
const itemArray = this._getItemsArray();
296301
const index = typeof item === 'number' ? item : itemArray.indexOf(item);
297302

298303
this._activeItemIndex = index;
@@ -314,17 +319,18 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
314319
* currently active item and the new active item. It will calculate differently
315320
* depending on whether wrap mode is turned on.
316321
*/
317-
private _setActiveItemByDelta(delta: -1 | 1, items = this._items.toArray()): void {
318-
this._wrap ? this._setActiveInWrapMode(delta, items)
319-
: this._setActiveInDefaultMode(delta, items);
322+
private _setActiveItemByDelta(delta: -1 | 1): void {
323+
this._wrap ? this._setActiveInWrapMode(delta) : this._setActiveInDefaultMode(delta);
320324
}
321325

322326
/**
323327
* Sets the active item properly given "wrap" mode. In other words, it will continue to move
324328
* down the list until it finds an item that is not disabled, and it will wrap if it
325329
* encounters either end of the list.
326330
*/
327-
private _setActiveInWrapMode(delta: -1 | 1, items: T[]): void {
331+
private _setActiveInWrapMode(delta: -1 | 1): void {
332+
const items = this._getItemsArray();
333+
328334
for (let i = 1; i <= items.length; i++) {
329335
const index = (this._activeItemIndex + (delta * i) + items.length) % items.length;
330336
const item = items[index];
@@ -341,17 +347,18 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
341347
* continue to move down the list until it finds an item that is not disabled. If
342348
* it encounters either end of the list, it will stop and not wrap.
343349
*/
344-
private _setActiveInDefaultMode(delta: -1 | 1, items: T[]): void {
345-
this._setActiveItemByIndex(this._activeItemIndex + delta, delta, items);
350+
private _setActiveInDefaultMode(delta: -1 | 1): void {
351+
this._setActiveItemByIndex(this._activeItemIndex + delta, delta);
346352
}
347353

348354
/**
349355
* Sets the active item to the first enabled item starting at the index specified. If the
350356
* item is disabled, it will move in the fallbackDelta direction until it either
351357
* finds an enabled item or encounters the end of the list.
352358
*/
353-
private _setActiveItemByIndex(index: number, fallbackDelta: -1 | 1,
354-
items = this._items.toArray()): void {
359+
private _setActiveItemByIndex(index: number, fallbackDelta: -1 | 1): void {
360+
const items = this._getItemsArray();
361+
355362
if (!items[index]) {
356363
return;
357364
}
@@ -366,4 +373,9 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
366373

367374
this.setActiveItem(index);
368375
}
376+
377+
/** Returns the items as an array. */
378+
private _getItemsArray(): T[] {
379+
return this._items instanceof QueryList ? this._items.toArray() : this._items;
380+
}
369381
}

src/lib/menu/menu-directive.ts

Lines changed: 54 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/Subscription';
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. */
@@ -83,18 +82,27 @@ const MAT_MENU_BASE_ELEVATION = 2;
8382
changeDetection: ChangeDetectionStrategy.OnPush,
8483
encapsulation: ViewEncapsulation.None,
8584
preserveWhitespaces: false,
85+
exportAs: 'matMenu',
8686
animations: [
8787
matMenuAnimations.transformMenu,
8888
matMenuAnimations.fadeInItems
8989
],
90-
exportAs: 'matMenu'
90+
providers: [
91+
{provide: MAT_MENU_PANEL, useExisting: MatMenu}
92+
]
9193
})
92-
export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestroy {
94+
export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel<MatMenuItem>, OnDestroy {
9395
private _keyManager: FocusKeyManager<MatMenuItem>;
9496
private _xPosition: MenuPositionX = this._defaultOptions.xPosition;
9597
private _yPosition: MenuPositionY = this._defaultOptions.yPosition;
9698
private _previousElevation: string;
9799

100+
/** Menu items inside the current menu. */
101+
private _items: MatMenuItem[] = [];
102+
103+
/** Emits whenever the amount of menu items changes. */
104+
private _itemChanges = new Subject<MatMenuItem[]>();
105+
98106
/** Subscription to tab events on the menu panel */
99107
private _tabSubscription = Subscription.EMPTY;
100108

@@ -105,7 +113,10 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
105113
_panelAnimationState: 'void' | 'enter' = 'void';
106114

107115
/** Emits whenever an animation on the menu completes. */
108-
_animationDone = new Subject<void>();
116+
_animationDone = new Subject<AnimationEvent>();
117+
118+
/** Whether the menu is animating. */
119+
_isAnimating: boolean;
109120

110121
/** Parent menu of the current menu panel. */
111122
parentMenu: MatMenuPanel | undefined;
@@ -141,9 +152,6 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
141152
/** @docs-private */
142153
@ViewChild(TemplateRef) templateRef: TemplateRef<any>;
143154

144-
/** List of the items inside of a menu. */
145-
@ContentChildren(MatMenuItem) items: QueryList<MatMenuItem>;
146-
147155
/**
148156
* Menu content that will be rendered lazily.
149157
* @docs-private
@@ -217,7 +225,7 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
217225
}
218226

219227
ngAfterContentInit() {
220-
this._keyManager = new FocusKeyManager<MatMenuItem>(this.items).withWrap().withTypeAhead();
228+
this._keyManager = new FocusKeyManager<MatMenuItem>(this._items).withWrap().withTypeAhead();
221229
this._tabSubscription = this._keyManager.tabOut.subscribe(() => this.close.emit('keydown'));
222230
}
223231

@@ -228,16 +236,10 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
228236

229237
/** Stream that emits whenever the hovered menu item changes. */
230238
_hovered(): Observable<MatMenuItem> {
231-
if (this.items) {
232-
return this.items.changes.pipe(
233-
startWith(this.items),
234-
switchMap(items => merge(...items.map(item => item._hovered)))
235-
);
236-
}
237-
238-
return this._ngZone.onStable
239-
.asObservable()
240-
.pipe(take(1), switchMap(() => this._hovered()));
239+
return this._itemChanges.pipe(
240+
startWith(this._items),
241+
switchMap(items => merge(...items.map(item => item._hovered)))
242+
);
241243
}
242244

243245
/** Handle a keyboard event from the menu, delegating to the appropriate action. */
@@ -315,6 +317,35 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
315317
}
316318
}
317319

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

330361
/** Callback that is invoked when the panel animation completes. */
331-
_onAnimationDone() {
332-
this._animationDone.next();
362+
_onAnimationDone(event: AnimationEvent) {
363+
this._animationDone.next(event);
364+
this._isAnimating = false;
333365
}
334366
}

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/Subject';
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 */
@@ -71,7 +73,8 @@ export class MatMenuItem extends _MatMenuItemMixinBase
7173
constructor(
7274
private _elementRef: ElementRef,
7375
@Inject(DOCUMENT) document?: any,
74-
private _focusMonitor?: FocusMonitor) {
76+
private _focusMonitor?: FocusMonitor,
77+
@Inject(MAT_MENU_PANEL) @Optional() private _parentMenu?: MatMenuPanel<MatMenuItem>) {
7578

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

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

@@ -100,6 +107,10 @@ export class MatMenuItem extends _MatMenuItemMixinBase
100107
this._focusMonitor.stopMonitoring(this._getHostElement());
101108
}
102109

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

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)