Reputation: 1507
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?
Upvotes: 13
Views: 7903
Reputation: 323
In order to get the state of isActive in the component, you need to wait for the AfterContentChecked lifecycle callback.
<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
Bob {{ rla.isActive ? '(already open)' : ''}}
</a>
@ViewChild('rla') private rla: RouterLinkActive;
ngAfterContentChecked(): void {
if (this.rla?.isActive) {
console.log('isActive')
}
}
Upvotes: 4
Reputation: 71
As an extension of Nayfin's answer, this also works (tested in Angular 11).
This is using the template variable to set a property, not as part of an ngFor. You have to use a different template variable for each component.
<a routerLink="/route1" routerLinkActive #route1RLA="routerLinkActive" [active]="route1RLA.isActive">Route 1</a>
<a routerLink="/route2" routerLinkActive #route2RLA="routerLinkActive" [active]="route2RLA.isActive">Route 2</a>
<a routerLink="/route3" routerLinkActive #route3RLA="routerLinkActive" [active]="route3RLA.isActive">Route 3</a>
Upvotes: 2
Reputation: 2141
you can get access to routerLinkActive with @ViewChild()
decorator
@ViewChild(RouterLinkActive) private routerLinkActive: RouterLinkActive;
but the problem here is that its values are not set immmediately, so for most cases during component render isActive
will be false, and only later Router will set it to true.
Upvotes: 2
Reputation: 395
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.
Upvotes: 14