需求描述
1、点击导航打开新页面
2、打开的新页面导航处于选中状态,样式包括图标、文字、下划线
出现的问题:
设置[class.active]=“acticeIndex == i” 打开新页面,新页面的导航并没有处于选中状态,但是原页面上点击到的导航处于选中状态
原因分析:
新页面中没有acticeIndex值
解决方法:
在nav组件中设置acticeIndex为输入型字段,在home、news、product组件中分别设置acticeIndex值为0,1,2,这样打开新页面时,就能获取到acticeIndex值,当acticeIndex == i就把active样式加载上
具体实现
新建nav组件,代码如下
<div class="nav">
<ul>
<li *ngFor="let item of navData; let i = index">
<a target="_blank" href={{item.link}} [class.active]="acticeIndex === i" (click)="handleClick(i)">
<div class="img" *ngIf="acticeIndex === i">
<img src="assets/nav/nav{{i}}-active.png">
</div>
<div class="img" *ngIf="acticeIndex !== i">
<img src="assets/nav/nav{{i}}.png">
</div>
<div class="name">{{item.name}}</div>
</a>
</li>
</ul>
</div>
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.scss']
})
export class NavComponent implements OnInit {
navData = [
{
name: '首页',
link: '/home',
},
{
name: '新闻',
link: '/news',
},
]
/**
* 在home、news、product中可以设置acticeIndex的值
* 在home组件中设置activeIndex=0时,首页文字、图标处于选中状态
* 在news组件中设置activeIndex=1时,新闻文字、图标处于选中状态
*/
@Input() acticeIndex = 0
constructor() { }
ngOnInit() {
}
// 点击打开新页面
handleClick(i) {
this.acticeIndex = i
}
}
.nav {
background: #e0e0e0;
li {
display: inline-block;
}
a {
text-decoration: none;
height: 90px;
display: block;
padding: 0 30px;
box-sizing: border-box;
color:#666;
&:hover {
color: #2c83d1;
}
}
img {
padding-top: 15px;
height: 30px;
width: 30px;
}
.active {
color: #2c83d1;
position: relative;
&::before {
content: '';
position: absolute;
bottom: 0;
height: 3px;
left: 0;
right: 0;
background: #2c83d1;
}
}
.name {
height: 24px;
padding-top: 3px;
}
}
新建home组件
<!--acticeIndex输入属性-->
<app-nav [acticeIndex]=acticeIndex></app-nav>
<div>我是首页</div>
home组件ts文件设置acticeIndex值
acticeIndex = 0
新建news组件
<!--acticeIndex输入属性-->
<app-nav [acticeIndex]=acticeIndex></app-nav>
<div>我是新闻组件</div>
news组件ts文件设置acticeIndex值
acticeIndex = 1
实现效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021062311212195.png