如何在Angular 2中使用*ngFor
迭代多维数组。
以下是我使用的DOM Wrapper:
<li *ngFor="let menuName of menuNames" routerLinkActive="active" [ngClass]="{'has-submenu':menuName.submenu?.length>0 }">
<a href="#" [routerLink]="menuName.route" *ngIf="!menuName.enableSM"> <i class="glyphicon {{menuName.icon}}"></i><span class="nav-label">{{menuName.name}}</span> </a>
<a href="#" *ngIf="menuName.enableSM"> <i class="glyphicon glyphicon-list-alt"></i> <span class="nav-label">Pages</span> </a>
<ul class="list-unstyled" *ngIf="menuName.enableSM">
<li *ngFor="let subMenuName of menuNames['submenu'] let idx = index;"> <a [routerLink]="subMenuName.route">404</a> </li>
</ul>
</li>
嵌套数组:
menuNames = [{
name: "Dashboard",
route: '/home',
icon: "glyphicon-th-large",
submenu: [],
enableSM: false
}, {
name: "Pages",
route: '',
icon: "glyphicon-list-alt",
submenu: [{
name: "404",
route: '/404.html'
}, {
name: "Signin",
route: '/auth/signin'
}],
enableSM: true
}];
第二个循环根本不渲染。
答案 0 :(得分:5)
您的代码中存在一些小问题,错别字。第二个*ngFor
应如下所示:
*ngFor="let subMenuName of menuName['submenu']; let idx = index;"
请注意menuName
而非menuNames
并且在let idx
之前有分号。