In Angular, How to Determine the Active Route

In Angular, how do you determine the active route?

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.)

How to get current route

The new V3 router has a url property.

this.router.url === '/login'

Angular 2 - Check current active route name

I believe there is an issue with Scott's answer where he uses the ActivatedRoute inside the constructor of the service. This route won't get updated.

I thought of another solution which might peek your interest. It again comes down on using the data property on the routes, but now using another resolve service:

You are going to need a RouterConfig like this, where for each route you add the state: StateResolve and a data object containing the state name:

const routes: RouterConfig = [{
path: 'queue/:date/:offset/:type',
component: BundleListComponent,
resolve: {
response: BundleListResolve,
state: StateResolve
},
data: {
state: 'Bundle'
},
...
]

don't forget to add the StateResolve service to the providers array

Your StateResolve service will look something like this:

@Injectable()
export class StateResolve implements Resolve<string> {

constructor(private stateService: StateService) {}

resolve(route: ActivatedRouteSnapshot): string {
let state: string = route.data['state']
this.stateService.setState(state);
return state;
}
}

Obviously you will need a StateService which has the setState method, but I guess from here it's pretty self-explanatory.

Perhaps using a resolve guard is a bit eccentric, but if you think about it, you are trying to resolve data before you show the route. In this case, the state inside the data variable, so it does make sense to use the Resolve to access the data property

Angular: How to determine active route with parameters?

Just check the auto-defined router-link-active class to a element.

In Angular, how to check the route is active for a relative route?

This is how I get it to work. If there is any better solution please feel free to chime in.

<a [ngClass]="{'active': item.route 
? router.isActive(router.createUrlTree([item.route], {relativeTo: route}).toString(), true)
: false">
{{item.displayName}}
</a>

How to get the active route in app.component

You have to "listen" to the router-events.

See my plunker for a working demo: https://plnkr.co/edit/XJmOa7rmtvBpuJDfQ2Vd?p=preview

The interesting part is this code snippet:

@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<a routerLink="/cmp1">cmp1</a><br />
<a routerLink="/cmp2">cmp2</a><br />
<a routerLink="/cmp3">cmp3</a><br />

<router-outlet></router-outlet>
`,
})
export class App {
name:string;
constructor(private _r: Router) {
this.name = 'Angular2'

this._r.events.subscribe(event => {
if (event instanceof RoutesRecognized) {
console.log('navigated to:', event.url);
console.log('route state', event.state);
console.log('');
}
else if (event instanceof NavigationEnd) {
// if u dont need the state, you could even use this event-type..
}
});
}
}

Subscribe to the router-events and check which type of event was fired.
If you want to use the state (params, queryParams, ...) i recommend to use RoutesRecognized-event-type. but you can even use NavigationEnd-event-type if you only want to get the current url..

Angular router active link based only on 1st route level

maybe you can try something like this:

<li class="nav-item"
<a class="nav-link" [routerLink]="['/offer/list']"
[class.active]="router.url.startsWith('/offer')"
routerLinkActive="active">
Offer Regions
</a>
</li>

I think this will give the desired result.



Related Topics



Leave a reply



Submit