Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Apply style to element depending on sibling RouterLinkActive?

I do not have only one menu bar on my app that I need to be painted when the user navigates, I have another components too that needs to be painted as well. Can I achieve this just using routerLinkActive?

menu.html

<menu>
  <a routerLink="page1" routerLinkActive="active">
      option1
  </a>
  <a routerLink="page2" routerLinkActive="active">
      option2
  </a>
</menu>

This menu works great. But what I'm asking is how can I take advantage of routerLinkActive property placed in other HTML Tag. like:

main.html

<main>
    <span class="title" routerLinkActive="active">My sub child part</span>
</main>
like image 309
napstercake Avatar asked Jun 05 '17 19:06

napstercake


3 Answers

you can apply the RouterLinkActive directive to an ancestor of a RouterLink.

<div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>

More details here.

Hope this helps!!

like image 167
Madhu Ranjan Avatar answered Sep 28 '22 08:09

Madhu Ranjan


You could bind the state of the routerLinkActive directive to whether or not a class is applied to an element as follows:

<a routerLink="page1" routerLinkActive="active" #rla="routerLinkActive"/>
<span [class.active-span]="rla.isActive"></span>

.active-span {
 background-color: red;
}

#rla is a template variable You can find more info about this use case of the RouterLinkActive directive in the docs

like image 26
Jota.Toledo Avatar answered Sep 28 '22 06:09

Jota.Toledo


You can call [class.active]="router.isActive('/parentUrlFragment',false)" on Parent Selector to have active class on the parent.

On your TS file :

import { Router, ActivatedRoute } from '@angular/router';
constructor(public router: Router){}

Now you can access the isActive method of Router in your html;

So if you have a Nested Menu Like :

Product
> Category 1
> Category 2

Selecting any of the Category Link will have active class on Product selector with [class.active]="router.isActive('/product',false)"

like image 32
Taufiq Ahmed Avatar answered Sep 28 '22 06:09

Taufiq Ahmed