angular 打开新页面,导航处于选中状态

需求描述
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在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值