子组件处于活动状态时,路由器链接处于活动状态

时间:2019-04-27 09:10:02

标签: angular

{ 
    path: 'dashboard',
    component: DashboardComponent, 
    children: [
        {
            path: '',
            component: DashboardHomeComponent,
            pathMatch: 'full',
        },
        {
            path: 'em',
            component: EmComponent,
        }
        {
            path: 'ec',
            component: EcComponent,
        }
    ]
}

如果用户使用em或ec组件,我希望li-bg类保留在dashbord菜单链接中。 我无法删除[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>

DashboardComponent

 <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

1 个答案:

答案 0 :(得分:0)

您还可以使用ngClass指令和Location类添加/删除带有父项的html标签的一个或多个css类。在此示例中,当某个组件方法(handleActiveClass)返回true且反之亦然时,将添加一个CSS类。这样,您可以根据用户当前处于哪个子页面来控制何时添加或删除父类。

DashboardComponent-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';
   }

}

DashboardComponent-HTML:

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