简体   繁体   中英

routerLinkActive for multiple routes

I want to apply 'active' class to my header nav bar. it is working well with the standard [ routerLinkActive ] but there is one issue. some of the <li> elements has two situations which makes them active.

I have [/something/inboxes] and [/something/details/:Id] and i want the something tab to be active for these two routes

this is my code:

  <li [routerLinkActive]="['active']">
    <a [routerLink]="['/something/inboxes']">something</a>
  </li>

Note that the inboxes and details are completely different components.

My question is, is there any better and easier way than using [ngClass]

我认为此答案可能会有所帮助: Angular4-routerLinkActive是否仅适用于相同的html标签?

I had a similar problem. I wanted link to be active for all child routes. I resolved it like this: HTML:

 <a class="{YOUR CLASS}" routerLink="/{my link}/test" [class.selected]="isActive('{my link}')"><a> 

If you have a different class for link active use [class.my-active-link-class]

TS:

 public isActive(url): boolean {
      return this.router.url.includes(url);
    } 

You can extend your isActive method to accept array of urls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM