NOTE: There are many different answers here, and most have been valid at one time or another. The fact is that what works has changed a number of times as the Angular team has changed its Router. The Router 3.0 version that will eventually be the router in Angular breaks many of these solutions, but offers a very simple solution of its own. As of RC.3, the preferred solution is to use [routerLinkActive]
as shown in this answer.
In an Angular application (current in the 2.0.0-beta.0 release as I write this), how do you determine what the currently active route is?
I'm working on an app that uses Bootstrap 4 and I need a way to mark navigation links/buttons as active when their associated component is being shown in a <router-output>
tag.
I realize that I could maintain the state myself when one of the buttons is clicked upon, but that wouldn't cover the case of having multiple paths into the same route (say a main navigation menu as well as a local menu in the main component).
Any suggestions or links would be appreciated. Thanks.
What is an activated route? The Angular Docs define the ActivatedRoute as. A service that is provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query params and the global fragment.
An active route is a route that is selected as the best path. Inactive routes are not displayed.
We can test routing in Angular by using RouterTestingModule instead of RouterModule to provide our routes. This uses a spy implementation of Location which doesn't trigger a request for a new URL but does let us know the target URL which we can use in our test specs.
Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.
With the new Angular router, you can add a [routerLinkActive]="['your-class-name']"
attribute to all your links:
<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>
Or the simplified non-array format if only one class is needed:
<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>
Or an even simpler format if only one class is needed:
<a [routerLink]="['/home']" routerLinkActive="is-active">Home</a>
See the poorly documented routerLinkActive
directive for more info. (I mostly figured this out via trial-and-error.)
UPDATE: Better documentation for the routerLinkActive
directive can now be found here. (Thanks to @Victor Hugo Arango A. in the comments below.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With