基于angular的菜单递归
基于angular的菜单递归
1. ngfor 顶层调用菜单组件
通过angular的for循环指令调用菜单树形数据结构。
<app-menu-item
*ngFor="let menuItem of menu"
[menuItem]="menuItem"
[isRoot]="true"
></app-menu-item>
2. 多级菜单的递归调用
菜单组件的ts文件,定义多级菜单默认都是闭合。
import { Component, OnInit, Input } from '@angular/core';
import { MenuItem } from '../models/menu-item';
@Component({
selector: 'app-menu-item',
templateUrl: './menu-item.component.html',
styleUrls: ['./menu-item.component.scss']
})
export class MenuItemComponent implements OnInit {
@Input() menuItem: MenuItem;
@Input() isRoot: boolean;
isOpen = false;
constructor() {}
ngOnInit() {}
onMenuItemSelected(menuItem: MenuItem): void {
console.log(menuItem);
}
}
- 定义多级菜单在有子菜单集合时为根菜单。定义菜单项的颜色,展开/闭合状态,点击事件(切换展开/闭合);
- 根据菜单状态值判断是否进行下级菜单的渲染;
- 定义当前菜单项为末级菜单时的模板;
<div>
<p *ngIf="menuItem.children; else finalItem">
<ion-button
[color]="isRoot ? 'primary' : 'secondary'"
[expand]="isRoot ? 'full' : 'block'"
(click)="isOpen = !isOpen"
>
{{ menuItem.name }}
</ion-button>
<span *ngIf="isOpen">
<app-menu-item
*ngFor="let item of menuItem.children"
[menuItem]="item"
></app-menu-item>
</span>
</p>
</div>
<ng-template #finalItem>
<p>
<ion-button color="light" expand="full" (click)="onMenuItemSelected(menuItem)">
{{ menuItem.name }}
</ion-button>
</p>
</ng-template>
3. 菜单模型
- 菜单名称,用于展示;
- 菜单id,用于数据结构编排;
- 子菜单集合,形成树形,便于展开;
export class MenuItem {
name: string;
id: number;
children: Array<MenuItem>;
}
4.菜单的json文件
menu-Item.ts,与3中的菜单模型数据结构保持一致生成。
export const menuItems = [
{
name: 'Appetizers',
id: 1,
children: [
{
name: 'Fresco Salsa',
id: 6,
children: null
}
]
},
{
name: 'Main dishes',
id: 2,
children: [
{
name: 'Beef',
id: 7,
children: [
{
name: 'Crispy Orange Beef',
id: 10,
children: null
}
]
},
{
name: 'Burger',
id: 8,
children: [
{
name: 'Chorizo Burger',
id: 11,
children: null
}
]
},
{
name: 'Vegetarian',
id: 9,
children: [
{
name: 'Chile Rellenos',
id: 12,
children: null
}
]
}
]
},
{
name: 'Side dishes',
id: 3,
children: [
{
name: 'Baked potato',
id: 13,
children: null
}
]
},
{
name: 'Salads',
id: 4,
children: [
{
name: 'Taco Slaw',
id: 14,
children: null
}
]
},
{
name: 'Desserts',
id: 5,
children: [
{
name: 'Crepes',
id: 15,
children: null
}
]
}
];
5 最终菜单效果图
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://www.cnblogs.com/JerryMouseLi/p/15843718.html
The Sky is the limit.