Angular实现二级导航栏
作者:摩羯的成长期
这篇文章主要为大家详细介绍了Angular实现二级导航栏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Angular实现二级导航栏的具体代码,供大家参考,具体内容如下
1、将菜单放入数据库:
模拟放到该路径下:
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>
实际效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。