diff --git a/packages/theme/src/services/menu/menu.service.spec.ts b/packages/theme/src/services/menu/menu.service.spec.ts index 1d62222ba..087295135 100644 --- a/packages/theme/src/services/menu/menu.service.spec.ts +++ b/packages/theme/src/services/menu/menu.service.spec.ts @@ -44,7 +44,7 @@ describe('Service: Menu', () => { }, { text: 'text', externalLink: '//ng-alain.com' }, { text: 'text', link: '/demo2', i18n: 'text' }, - { text: 'sub', children: [] }, + { text: 'sub', children: [{ text: 'text', link: '/test', badge: 10 }] }, { text: 'hide', link: '/hide', hide: true } ]; @@ -342,6 +342,12 @@ describe('Service: Menu', () => { const res = srv.find({ url: `/always-first-item`, cb: _ => true }); expect(res).toBe(srv.menus[0]); }); + it('return last item', () => { + const first = srv.find({ url: `/test` }); + expect((first as NzSafeAny)._parent == null).toBe(true); + const last = srv.find({ url: `/test`, last: true }); + expect((last as NzSafeAny)._parent != null).toBe(true); + }); }); describe('#open', () => { diff --git a/packages/theme/src/services/menu/menu.service.ts b/packages/theme/src/services/menu/menu.service.ts index 425eebe19..c3ef60013 100644 --- a/packages/theme/src/services/menu/menu.service.ts +++ b/packages/theme/src/services/menu/menu.service.ts @@ -211,8 +211,14 @@ export class MenuService implements OnDestroy { * 是否忽略隐藏的项,默认:`false` */ ignoreHide?: boolean; + /** + * Whether to return the last one, default: `false` + * + * 是否返回最后一个,默认:`false` + */ + last?: boolean; }): Menu | null { - const opt = { recursive: false, ignoreHide: false, ...options }; + const opt = { recursive: false, ignoreHide: false, last: false, ...options }; if (opt.key != null) { return this.getItem(opt.key); } @@ -223,12 +229,15 @@ export class MenuService implements OnDestroy { while (!item && url) { this.visit(opt.data ?? this.data, i => { + if (!opt.last && item != null) { + return; + } if (opt.ignoreHide && i.hide) { return; } if (opt.cb) { const res = opt.cb(i); - if (!item && typeof res === 'boolean' && res) { + if (typeof res === 'boolean' && res) { item = i; } }