Dynamic nested Material menu from json object in Angular 5

rain01 picture rain01 · Jan 8, 2018 · Viewed 27k times · Source

How to create dynamic nested menu from json object?

I started using Angular Material Design today for the first time and I'm trying to create nested menus using material design. The documentation is pretty straight forward for static stuff.

But I need to create dynamic nested menu from json object and I can't find a simple solution to this anywhere. It just needs to be one level deep.

json object(not set in stone):

my_menu = {
    'main1': ['sub1', 'sub2'],
    'main2': ['sub1', 'sub2'],
}

which would generate something like this but dynamically: expected result example at stackblitz

how it looks

I tried building it running *ngFor like this for main menu and then separate on each sub menu but it ended in errors.

<button mat-button [matMenuTriggerFor]="main_menu">My menu</button>

<mat-menu #main_menu="matMenu">
  <button *ngFor="let main_item of objectKeys(my_menu)" mat-menu-item [matMenuTriggerFor]="main_item">{{ main_item }}</button>
  <button mat-menu-item [matMenuTriggerFor]="main2">main2</button>
</mat-menu>

<mat-menu *ngFor="let sub_menu of objectKeys(my_menu)" #sub_menu="matMenu">
  <button *ngFor="let sub_name of sub_menu" mat-menu-item>{{ sub_name }}</button>
</mat-menu>

I know it's wrong but that's where my understanding of angular ended.

objectKeys just returns all the keys of the object using Object.keys which is loaded from the ts file.

objectKeys = Object.keys;

PS. I'm fairly new to Angular also

Answer

yurzui picture yurzui · Jan 8, 2018

The following structure should work for you:

<button mat-button [matMenuTriggerFor]="main_menu">My menu</button>

<mat-menu #main_menu="matMenu">
  <ng-container *ngFor="let mainItem of objectKeys(my_menu)">
    <button mat-menu-item [matMenuTriggerFor]="sub_menu">{{ mainItem }}</button>
    <mat-menu #sub_menu="matMenu">
       <button *ngFor="let subItem of my_menu[mainItem]" mat-menu-item>{{ subItem }}</button>
    </mat-menu>
  </ng-container>
</mat-menu>

Since I placed sub_menu inside the embedded template (*ngFor) we can use the same name for template reference variable(#sub_menu).

Stackblitz Example