我想基于具有父子结构的API接收到的数据,为下拉菜单生成嵌套项目。
我有一个用于创建用户的表单,在此表单中,我有下拉菜单选择
其数据是关于每个ou具有父子关系的组织单位。
我的管理员由于要以线性模式显示ou而想要创建用户时感到困惑,并且想要在嵌套视图中显示这些用户,您能帮我吗?
我的数据结构是:
export class DisplayOu {
id: number;
parentId: number;
name: string;
cssClass: string;
imageUrl: string;
designation: number;
subordinates: DisplayOu[] = []
}
最佳答案
根据您对您的问题所做的分析,我已经解决了该问题。我注意到您正在同一类中创建DisplayOu
的数组对象。我已经固定为父菜单和子菜单使用不同的界面,如下所示:
interface MainMenu {
id: number;
parentId: number;
name: string;
cssClass: string;
imageUrl: string;
designation: number;
subMenus:SubMenu[];
}
interface SubMenu {
id: number;
parentId: number;
name: string;
cssClass: string;
imageUrl: string;
designation: number;
}
为了获取数据,我创建了const对象(在您的情况下,它是来自API的结果),如下所示:
const menu: MainMenu[] = [
{
id: 1,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "John",
parentId: 1,
subMenus: [
{
id: 2,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Loream Ipsum 1",
parentId: 1
},
{
id: 3,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Loream Ipsum 2",
parentId: 1
},
{
id: 4,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Loream Ipsum 3 ",
parentId: 1
},
{
id: 5,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Loream Ipsum 4",
parentId: 1
}
]
},
{
id: 6,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Andy",
parentId: 1,
subMenus: [
{
id: 7,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Loream Ipsum 5",
parentId: 1
},
{
id: 8,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Loream Ipsum 6",
parentId: 1
},
{
id: 9,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Loream Ipsum 7",
parentId: 1
},
{
id: 10,
cssClass: "foo",
designation: 3,
imageUrl: "",
name: "Loream Ipsum 8",
parentId: 1
}
]
}
];
并在这样的组件中初始化:
menuItem: MainMenu[];
constructor() {
this.menuItem = menu;
console.log(this.menuItem);
}
然后在
html
中显示如下: <ul class="navbar-nav mr-auto">
<li class="nav-item dropdown" dropdown *ngFor="let menu of menuItem">
<a class="nav-link dropdown-toggle" href (click)="false" id="navbarDropdown" role="button" aria-controls="navbarDropdown" dropdownToggle>
{{menu.name}} <span class="caret"></span>
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown" *dropdownMenu role="menu" aria-labelledby="navbarDropdown">
<li *ngFor="let subMenu of menu.subMenus">
<a class="dropdown-item" href="#">{{subMenu.name}}</a>
</li>
</ul>
</li>
</ul>
工作中的stackblitz demo is here。我希望这可以帮助你。
关于html - 创建父子数据的嵌套下拉菜单,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58145046/