You can combine mat-sidenav
with mat-tree
to achieve this. This can be done without any 'hacky' fixes, which are needed if you try to use mat-accordion
instead.
I created this Stackblitz example that shows the result.
HTML:
<mat-nav-list>
<mat-tree [dataSource]="menuItems" [treeControl]="menuTreeControl">
<mat-tree-node *matTreeNodeDef="let menuItem">
<a
[routerLink]="menuItem.link"
mat-list-item
routerLinkActive="mdc-list-item--activated"
>
{{ menuItem.name }}
</a>
</mat-tree-node>
<mat-nested-tree-node *matTreeNodeDef="let menuItem; when: hasChild">
<a mat-list-item matTreeNodeToggle>
<span matListItemTitle
>{{ menuItem.name }}
<mat-icon>
{{
menuTreeControl.isExpanded(menuItem)
? "expand_more"
: "expand_less"
}}
</mat-icon>
</span>
</a>
<div *ngIf="menuTreeControl.isExpanded(menuItem)" role="group">
<ng-container matTreeNodeOutlet></ng-container>
</div>
</mat-nested-tree-node>
</mat-tree>
</mat-nav-list>
SCSS:
mat-nav-list {
div[role="group"] {
padding-left: 20px;
}
mat-icon {
position: absolute;
right: 20px;
}
}
Component:
export class NavMenuComponent {
previewEnabled = Cookies.get("previewEnabled") === "true";
title$: Observable<string>;
menuTreeControl = new NestedTreeControl<MenuItem>(
(menuItem) => menuItem.children
);
menuItems: MenuItem[] = [
{ type: "link", link: "link-1", name: "Item 1"},
{
type: "section",
name: "Parent Item",
children: [
{ type: "link", link: "link-2", name: "Item 2" },
{ type: "link", link: "link-3", name: "Item 3" },
],
},
];
constructor(
private router: Router,
) {
router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.subscribe(() => this.openActiveRouteParentMenuItem());
}
openActiveRouteParentMenuItem() {
_.forEach(this.menuItems, (parentMenuItem) => {
const childMenuItems = this.menuTreeControl.getChildren(
parentMenuItem
) as MenuItem[];
_.forEach(childMenuItems, (childMenuItem) => {
if (
this.router.isActive(childMenuItem.link as string, {
paths: "subset",
queryParams: "subset",
fragment: "ignored",
matrixParams: "ignored",
})
) {
this.menuTreeControl.expand(parentMenuItem);
}
});
});
}
hasChild = (_: number, menuItem: MenuItem) => !!menuItem.children?.length;
}
interface MenuItem {
type: "link" | "section";
name: string;
link?: string;
children?: MenuItem[];
}