MichaelOryl MichaelOryl - 4 years ago 5523
Javascript Question

In Angular 2 how do you determine the active route?

In an Angular 2 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.

Answer Source

You can check the current route by injecting the Location object into your controller and checking the path like so:

class MyController {
    constructor(private _location: Location) {}
    public getPath() { return this._location.path() }
}

You will have to make sure to import it first:

import {Location} from "angular2/router";

You can then use a regular expression to match against the path that's returned to see which route is active. Note that the Location class returns a normalized path regardless of which LocationStrategy you're using. So even if you're using the HashLocationStragegy the paths returned will still be of the form /foo/bar not #/foo/bar

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download