Angular二级导航栏
摩羯的成长期 人气:01、将菜单放入数据库:
模拟放到该路径下:
src/assets/json/header.json
{ "siteName": "PGG娱乐健身中心", "menu":[ { "id":"1", "menuName":"首页", "menuChildren": [{}], "showSubMenu": false }, { "id":"2", "menuName":"健身中心", "menuChildren": [ { "itemId": "1", "menuChidrenItem": "居室器械健身" }, { "itemId": "2", "menuChidrenItem": "野外运动" }, { "itemId": "3", "menuChidrenItem": "健身小知识" } ], "showSubMenu": false }, { "id":"3", "menuName":"休闲娱乐", "menuChildren": [ { "itemId": "1", "menuChidrenItem": "养生钓鱼" }, { "itemId": "2", "menuChidrenItem": "野炊烧烤" }, { "itemId": "3", "menuChidrenItem": "真人野战" } ], "showSubMenu": false }, { "id":"4", "menuName":"订单中心", "menuChildren": [ { "itemId": "1", "menuChidrenItem": "所有订单" }, { "itemId": "2", "menuChidrenItem": "已完成订单" }, { "itemId": "3", "menuChidrenItem": "未完成订单" } ], "showSubMenu": false }, { "id":"5", "menuName":"个人中心", "menuChildren": [ { "itemId": "1", "menuChidrenItem": "用户信息修改" } ], "showSubMenu": false } ] }
ts接受数据,并处理:
import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpClientModule } from '@angular/common/http'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { headData: any; constructor( private http: HttpClient ) { } ngOnInit(): void { // http://localhost:4200/assets/json/header.json 可访问 this.http.get('/assets/json/header.json').subscribe(data => { this.headData = data; console.log(this.headData.menu); }); } showSubMenu(item: any, index: any): void { // 设置当前子菜单显示 item.showSubMenu = true; } notShowSubMenu(item: any, index: any): void { // 设置当前子菜单不显示 item.showSubMenu = false; } }
html显示控制,利用ngstyle控制:
<div class="menu_container"> <div id="top_title">{{headData.siteName}}</div> <div id="menu" *ngFor="let item of headData.menu, let i = index"> <!-- 第一个参数为类名称,第二个参数为boolean值,如果为true就添加第一个参数的类--> <ul [ngClass]="{'sumMenu': item.showSubMenu}"> <!--mouseleave mouseout供选则--> <li class="top_nav nav_1" (mouseenter)="showSubMenu(item ,i)" (mouseleave)="notShowSubMenu(item, i)"> <span>{{item.menuName}}</span> <dl *ngFor="let child of item.menuChildren, let k = index" [ngStyle]="{'display': item.showSubMenu ? 'block':'none','margin-left': '-2.6rem'}"> <dd>{{child.menuChidrenItem}}</dd> </dl> </li> </ul> </div> </div>
实际效果:
加载全部内容