【问题标题】:Router link active when child component is active当子组件处于活动状态时,路由器链接处于活动状态
【发布时间】:2019-04-27 09:10:01
【问题描述】:
{ 
    path: 'dashboard',
    component: DashboardComponent, 
    children: [
        {
            path: '',
            component: DashboardHomeComponent,
            pathMatch: 'full',
        },
        {
            path: 'em',
            component: EmComponent,
        }
        {
            path: 'ec',
            component: EcComponent,
        }
    ]
}

如果用户转到 em 或 ec 组件,我希望 li-bg 类留在仪表板菜单链接中。 我不能删除 [routerLinkActiveOptions]="{exact: true}" 因为那样它将对所有以 /dashboard 开头的链接都有效 有什么办法吗。

仪表板主页 HTML

<div class="row">
    <div class="col">
        <a routerLink="/dashboard/em">Em Service</a>
    </div>
    <div class="col">
        <a routerLink="/dashboard/ec">Ec Service</a>
    </div>
</row>

仪表板组件

 <div class="Sidebar">
    <a routerLinkActive="li-bg" [routerLinkActiveOptions]="{exact: true}" routerLink="/">Dashboard</a>
    <a routerLink="/dashboard/my-profile">My profile</a>
  </div>

链接

dashboard/ is home
dashboard/em is em component
dashboard/ec is e component

【问题讨论】:

  • 您可以使用routerLinkActive="router-link-active"激活当前活动链接

标签: angular


【解决方案1】:

您还可以使用ngClass 指令和Location 类来添加/删除一个或多个带有parant html-tag 的css 类。在此示例中,当某个组件方法 (handleActiveClass) 返回 true 时添加一个 css 类,反之亦然。通过这种方式,您可以根据用户当前所在的子页面来控制何时添加或删除父类。

仪表板组件-TS:

import {Location} from '@angular/common';

class DashboardComponent{

   constructor(private location: Location) {

   }

   handleActiveClass(){
     let relativePath: string = this.location.path();
     return relativePath === '/dashboard/em' || relativePath === '/dashboard/ec';
   }

}

仪表板组件-HTML:

<a [ngClass]="{'li-bg':handleActiveClass()}"
   routerLink="/">Dashboard</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2019-04-15
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多