我正在使用Angular7 * ngFor渲染带有子菜单的菜单,并且在渲染2D数组时遇到了问题。我的json数据是这样的:
{
"items": [
{
"id": 1,
"name" : "Talent",
"color" : "",
"subItems" : [],
"icon" : ""
},
{
"id": 2,
"name": "Connections",
"color" : "",
"isActivated" : false,
"subItems" : [
{
"id" : 1,
"name": "Pipelines",
"color": "",
"subItems" :[],
"icon" : "fa fa-caret-down"
},
{
"id" : 2,
"name": "Requisition",
"color": "",
"subItems" :[],
"icon" : ""
},
{
"id" : 3,
"name": "Projects",
"color": "",
"subItems" :[],
"icon" : ""
}
],
"icon" : ""
},
{
"id": 3,
"name": "Intelligence",
"color" : "",
"isActivated" : false,
"subItems" : [
{
"id" : 1,
"name": "Companies",
"color": "",
"subItems" :[],
"icon" : "fa fa-caret-down"
},
{
"id" : 2,
"name": "Schools",
"color": "",
"subItems" :[],
"icon" : ""
}
],
"icon" : ""
},
...
}
我要创建的菜单栏,结构非常像这样:
https://codepen.io/marong125/pen/wOZgGz
我重组了数据并存储在2D数组子项中,如下所示:
(2) [Array(3), Array(2)]
0: Array(3)
0: {id: 1, name: "Pipelines", color: "", subItems: Array(0), icon: "fa fa-caret-down"}
1: {id: 2, name: "Requisition", color: "", subItems: Array(0), icon: ""}
2: {id: 3, name: "Projects", color: "", subItems: Array(0), icon: ""}
length: 3
__proto__: Array(0)
1: Array(2)
0: {id: 1, name: "Companies", color: "", subItems: Array(0), icon: "fa fa-caret-down"}
1: {id: 2, name: "Schools", color: "", subItems: Array(0), icon: ""}
length: 2
我创建了导航部件,但子菜单部分工作得不是很好。当我喜欢这样的时候:
<nav>
<ul>
<li class="sub-menu" *ngFor="let navItem of navItems" (click)="expand(navItem.name, $event.target)">
<a href="#">{{navItem.name}}<span id="upDownIcons"><i *ngIf="navItem.subItems.length !== 0" [ngClass]="navIcons?.arrowDown" aria-hidden="true"></i></span></a>
<ul>
<ng-container *ngFor="let subItem of subItems; let i = index">
<ng-container *ngFor="let item of subItem; let j = index">
<li ><a href="#">{{item.name}}</a></li>
</ng-container>
</ng-container>
</ul>
</li>
</ul>
</nav>
有没有更好的解决方案来正确渲染2D数组?非常感谢!
你应该迭代subItems
的navItem
数组和subItem
的相同。
<li class="sub-menu" *ngFor="let navItem of navItems" (click)="expand(navItem.name, $event.target)">
<a href="#">{{navItem.name}}<span id="upDownIcons"><i *ngIf="navItem.subItems.length !== 0" [ngClass]="navIcons?.arrowDown" aria-hidden="true"></i></span></a>
<ul>
<ng-container *ngFor="let subItem of navItem.subItems; let i = index"> // Iterate over subItems of navItem
<ng-container *ngFor="let item of subItem.subItems; let j = index"> // The same here
<li ><a href="#">{{item.name}}</a></li>
</ng-container>
</ng-container>
</ul>
</li>
迭代你的navItems
并使用它的index
迭代它的subItems
<nav>
<ul>
<li class="sub-menu" *ngFor="let navItem of navItems;let i = index" (click)="expand(navItem.name, $event.target)">
<a href="#">{{navItem.name}}<span id="upDownIcons"><i *ngIf="navItem.subItems.length !== 0" [ngClass]="navIcons?.arrowDown" aria-hidden="true"></i></span></a>
<ul>
<ng-container *ngFor="let subItem of subItems[i]; let j = index">
<li ><a href="#">{{item.name}}</a></li>
</ng-container>
</ul>
</li>
</ul>
</nav>