这篇文章主要介绍了Angular如何实现二级导航栏,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
具体内容如下
将菜单放入数据库:
模拟放到该路径下:
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>
实际效果:
感谢你能够认真阅读完这篇文章,希望小编分享的“Angular如何实现二级导航栏”这篇文章对大家有帮助,同时也希望大家多多支持编程网,关注编程网行业资讯频道,更多相关知识等着你来学习!