Skip to content

Commit a18d631

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 653d8dc commit a18d631

File tree

7 files changed

+279
-55
lines changed

7 files changed

+279
-55
lines changed

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

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

53-
constructor(private _items: QueryList<T>) {
54-
_items.changes.subscribe((newItems: QueryList<T>) => {
55-
if (this._activeItem) {
56-
const itemArray = newItems.toArray();
57-
const newIndex = itemArray.indexOf(this._activeItem);
58-
59-
if (newIndex > -1 && newIndex !== this._activeItemIndex) {
60-
this._activeItemIndex = newIndex;
53+
constructor(private _items: QueryList<T> | T[]) {
54+
if (_items instanceof QueryList) {
55+
_items.changes.subscribe((newItems: QueryList<T>) => {
56+
if (this._activeItem) {
57+
const itemArray = newItems.toArray();
58+
const newIndex = itemArray.indexOf(this._activeItem);
59+
60+
if (newIndex > -1 && newIndex !== this._activeItemIndex) {
61+
this._activeItemIndex = newIndex;
62+
}
6163
}
62-
}
63-
});
64+
});
65+
}
6466
}
6567

6668
/**
@@ -120,7 +122,7 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
120122
filter(() => this._pressedLetters.length > 0),
121123
map(() => this._pressedLetters.join(''))
122124
).subscribe(inputString => {
123-
const items = this._items.toArray();
125+
const items = this._getItemsArray();
124126

125127
// Start at 1 because we want to start searching at the item immediately
126128
// following the current active item.
@@ -148,7 +150,7 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
148150
const previousIndex = this._activeItemIndex;
149151

150152
this._activeItemIndex = index;
151-
this._activeItem = this._items.toArray()[index];
153+
this._activeItem = this._getItemsArray()[index];
152154

153155
if (this._activeItemIndex !== previousIndex) {
154156
this.change.next(index);
@@ -259,17 +261,18 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
259261
* currently active item and the new active item. It will calculate differently
260262
* depending on whether wrap mode is turned on.
261263
*/
262-
private _setActiveItemByDelta(delta: -1 | 1, items = this._items.toArray()): void {
263-
this._wrap ? this._setActiveInWrapMode(delta, items)
264-
: this._setActiveInDefaultMode(delta, items);
264+
private _setActiveItemByDelta(delta: -1 | 1): void {
265+
this._wrap ? this._setActiveInWrapMode(delta) : this._setActiveInDefaultMode(delta);
265266
}
266267

267268
/**
268269
* Sets the active item properly given "wrap" mode. In other words, it will continue to move
269270
* down the list until it finds an item that is not disabled, and it will wrap if it
270271
* encounters either end of the list.
271272
*/
272-
private _setActiveInWrapMode(delta: -1 | 1, items: T[]): void {
273+
private _setActiveInWrapMode(delta: -1 | 1): void {
274+
const items = this._getItemsArray();
275+
273276
for (let i = 1; i <= items.length; i++) {
274277
const index = (this._activeItemIndex + (delta * i) + items.length) % items.length;
275278
const item = items[index];
@@ -286,17 +289,18 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
286289
* continue to move down the list until it finds an item that is not disabled. If
287290
* it encounters either end of the list, it will stop and not wrap.
288291
*/
289-
private _setActiveInDefaultMode(delta: -1 | 1, items: T[]): void {
290-
this._setActiveItemByIndex(this._activeItemIndex + delta, delta, items);
292+
private _setActiveInDefaultMode(delta: -1 | 1): void {
293+
this._setActiveItemByIndex(this._activeItemIndex + delta, delta);
291294
}
292295

293296
/**
294297
* Sets the active item to the first enabled item starting at the index specified. If the
295298
* item is disabled, it will move in the fallbackDelta direction until it either
296299
* finds an enabled item or encounters the end of the list.
297300
*/
298-
private _setActiveItemByIndex(index: number, fallbackDelta: -1 | 1,
299-
items = this._items.toArray()): void {
301+
private _setActiveItemByIndex(index: number, fallbackDelta: -1 | 1): void {
302+
const items = this._getItemsArray();
303+
300304
if (!items[index]) {
301305
return;
302306
}
@@ -311,4 +315,9 @@ export class ListKeyManager<T extends ListKeyManagerOption> {
311315

312316
this.setActiveItem(index);
313317
}
318+
319+
/** Returns the items as an array. */
320+
private _getItemsArray(): T[] {
321+
return this._items instanceof QueryList ? this._items.toArray() : this._items;
322+
}
314323
}

src/lib/menu/menu-directive.ts

Lines changed: 52 additions & 21 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,
@@ -35,14 +33,16 @@ import {
3533
import {Observable} from 'rxjs/Observable';
3634
import {merge} from 'rxjs/observable/merge';
3735
import {Subscription} from 'rxjs/Subscription';
36+
import {Subject} from 'rxjs/Subject';
3837
import {matMenuAnimations} from './menu-animations';
3938
import {throwMatMenuInvalidPositionX, throwMatMenuInvalidPositionY} from './menu-errors';
4039
import {MatMenuItem} from './menu-item';
41-
import {MatMenuPanel} from './menu-panel';
40+
import {MatMenuPanel, MAT_MENU_PANEL} from './menu-panel';
4241
import {MatMenuContent} from './menu-content';
4342
import {MenuPositionX, MenuPositionY} from './menu-positions';
4443
import {coerceBooleanProperty} from '@angular/cdk/coercion';
4544
import {FocusOrigin} from '@angular/cdk/a11y';
45+
import {AnimationEvent} from '@angular/animations';
4646

4747

4848
/** Default `mat-menu` options that can be overridden. */
@@ -76,18 +76,27 @@ const MAT_MENU_BASE_ELEVATION = 2;
7676
changeDetection: ChangeDetectionStrategy.OnPush,
7777
encapsulation: ViewEncapsulation.None,
7878
preserveWhitespaces: false,
79+
exportAs: 'matMenu',
7980
animations: [
8081
matMenuAnimations.transformMenu,
8182
matMenuAnimations.fadeInItems
8283
],
83-
exportAs: 'matMenu'
84+
providers: [
85+
{provide: MAT_MENU_PANEL, useExisting: MatMenu}
86+
]
8487
})
85-
export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestroy {
88+
export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel<MatMenuItem>, OnDestroy {
8689
private _keyManager: FocusKeyManager<MatMenuItem>;
8790
private _xPosition: MenuPositionX = this._defaultOptions.xPosition;
8891
private _yPosition: MenuPositionY = this._defaultOptions.yPosition;
8992
private _previousElevation: string;
9093

94+
/** Menu items inside the current menu. */
95+
private _items: MatMenuItem[] = [];
96+
97+
/** Emits whenever the amount of menu items changes. */
98+
private _itemChanges = new Subject<MatMenuItem[]>();
99+
91100
/** Subscription to tab events on the menu panel */
92101
private _tabSubscription = Subscription.EMPTY;
93102

@@ -97,6 +106,12 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
97106
/** Current state of the panel animation. */
98107
_panelAnimationState: 'void' | 'enter' = 'void';
99108

109+
/** Emits whenever an animation on the menu completes. */
110+
_animationDone = new Subject<AnimationEvent>();
111+
112+
/** Whether the menu is animating. */
113+
_isAnimating: boolean;
114+
100115
/** Parent menu of the current menu panel. */
101116
parentMenu: MatMenuPanel | undefined;
102117

@@ -128,9 +143,6 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
128143
/** @docs-private */
129144
@ViewChild(TemplateRef) templateRef: TemplateRef<any>;
130145

131-
/** List of the items inside of a menu. */
132-
@ContentChildren(MatMenuItem) items: QueryList<MatMenuItem>;
133-
134146
/**
135147
* Menu content that will be rendered lazily.
136148
* @docs-private
@@ -196,7 +208,7 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
196208
}
197209

198210
ngAfterContentInit() {
199-
this._keyManager = new FocusKeyManager<MatMenuItem>(this.items).withWrap().withTypeAhead();
211+
this._keyManager = new FocusKeyManager<MatMenuItem>(this._items).withWrap().withTypeAhead();
200212
this._tabSubscription = this._keyManager.tabOut.subscribe(() => this.close.emit('keydown'));
201213
}
202214

@@ -207,16 +219,10 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
207219

208220
/** Stream that emits whenever the hovered menu item changes. */
209221
_hovered(): Observable<MatMenuItem> {
210-
if (this.items) {
211-
return this.items.changes.pipe(
212-
startWith(this.items),
213-
switchMap(items => merge(...items.map(item => item._hovered)))
214-
);
215-
}
216-
217-
return this._ngZone.onStable
218-
.asObservable()
219-
.pipe(take(1), switchMap(() => this._hovered()));
222+
return this._itemChanges.pipe(
223+
startWith(this._items),
224+
switchMap(items => merge(...items.map(item => item._hovered)))
225+
);
220226
}
221227

222228
/** Handle a keyboard event from the menu, delegating to the appropriate action. */
@@ -294,6 +300,30 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
294300
}
295301
}
296302

303+
/**
304+
* Registers a menu item with the menu.
305+
* @docs-private
306+
*/
307+
addItem(item: MatMenuItem) {
308+
if (this._items.indexOf(item) === -1) {
309+
this._items.push(item);
310+
this._itemChanges.next(this._items);
311+
}
312+
}
313+
314+
/**
315+
* Removes an item from the menu.
316+
* @docs-private
317+
*/
318+
removeItem(item: MatMenuItem) {
319+
const index = this._items.indexOf(item);
320+
321+
if (this._items.indexOf(item) > -1) {
322+
this._items.splice(index, 1);
323+
this._itemChanges.next(this._items);
324+
}
325+
}
326+
297327
/** Starts the enter animation. */
298328
_startAnimation() {
299329
// @deletion-target 6.0.0 Combine with _resetAnimation.
@@ -307,7 +337,8 @@ export class MatMenu implements OnInit, AfterContentInit, MatMenuPanel, OnDestro
307337
}
308338

309339
/** Callback that is invoked when the panel animation completes. */
310-
_onAnimationDone(_event: AnimationEvent) {
311-
// @deletion-target 6.0.0 Not being used anymore. To be removed.
340+
_onAnimationDone(event: AnimationEvent) {
341+
this._animationDone.next(event);
342+
this._isAnimating = false;
312343
}
313344
}

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;
@@ -29,4 +35,6 @@ export interface MatMenuPanel {
2935
setPositionClasses: (x: MenuPositionX, y: MenuPositionY) => void;
3036
setElevation?(depth: number): void;
3137
lazyContent?: MatMenuContent;
38+
addItem?: (item: T) => void;
39+
removeItem?: (item: T) => void;
3240
}

0 commit comments

Comments
 (0)