Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access [routerLinkActive] value in component class

I have a tab component TabComponent which has the following HTML template:

<a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a>
<button>Close tab</button>

I would like to access the value of the [routerLinkActive] property, basically I would like to get a variable inside the component class that indicates if this routerLink is active. How can I access it from within the component class?

EDIT: I think if I can get access to the CSS class of the <a> link tag the work is done, is there a way to access it?

like image 529
Platus Avatar asked Jul 15 '16 12:07

Platus


People also ask

How do I know if my routerLink is active?

routerLinkActive is simply an indicator of whether this link represents the active route. @jessepinho - Tried it - [routerLinkActive]="'active'" will only work if you also have [routerLink] in the a-tag. If you had (click)="navitageTo('/route')" instead of [routerLink], and in that function, you called this.

What is routerLinkActive?

RouterLinkActivelinkTracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active.


1 Answers

I don't know if this will help at all but, you can get the values in your template like this:

<a *ngFor="let child of directory; let i = index;"
   routerLink="{{child.route}}"
   routerLinkActive #rla="routerLinkActive">

   <h3>{{rla.isActive}}</h3><!--Displays boolean indicating whether or not you are navigated to this link-->
</a>

Now, a boolean will display in your h3 indicating whether or not you are currently navigated to the link.

While this works as a template variable, I have been unable to pass the value to the component.ts or pass it to other template directives e.g

 <a *ngFor="let child of directory; let i = index;"
   routerLink="{{child.route}}"
   routerLinkActive #rla="routerLinkActive"

   [active]="rla.isActive" <!--This doesn't insert the boolean here for some reason-->
   >    
   <h3>{{rla.isActive}}</h3>
</a>

I hope this helps. Please update if you get any closer to a good solution.

like image 67
Nayfin Avatar answered Sep 22 '22 07:09

Nayfin