来自Angular 5中json对象的动态嵌套Material菜单 [英] Dynamic nested Material menu from json object in Angular 5

查看:55
本文介绍了来自Angular 5中json对象的动态嵌套Material菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从json对象创建动态嵌套菜单?

How to create dynamic nested menu from json object?

我今天第一次开始使用Angular Material Design,我正在尝试使用Material Design创建嵌套菜单. 文档对于静态内容非常简单.

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.

但是我需要从json对象创建动态嵌套菜单,并且在任何地方都找不到针对此的简单解决方案.它只需要深入一层即可.

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对象(未固定):

json object(not set in stone):

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

这将生成类似但动态的内容:预期结果示例在stackblitz中

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

我尝试过在主菜单上像这样运行*ngFor来构建它,然后在每个子菜单上将其分开,但最终以错误结束.

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仅使用从ts文件加载的Object.keys返回对象的所有键.

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

objectKeys = Object.keys;

PS.我对Angular也很陌生

PS. I'm fairly new to Angular also

推荐答案

以下结构应该适合您:

<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>

由于我将sub_menu放置在嵌入式模板(*ngFor)内,因此我们可以对模板引用变量(#sub_menu)使用相同的名称.

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

Stackblitz示例

Stackblitz Example

这篇关于来自Angular 5中json对象的动态嵌套Material菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆