I know I can use [routerLinkActive]="['active']"
, in fact I'm using it and works fine when I click the button on navbar and redirect's to example.com/home
, but if I use only example.com
, the is no active class, /home
and only the url are the same component, how can I solve this?
Asked
Active
Viewed 161 times
-2

Jaume Sastre
- 55
- 1
- 12
1 Answers
0
You can use a redirect in your routing module
const routes: Routes = [
{ path: "", redirectTo: "home", pathMatch: "full" },
{ path: "**", component: PageNotFoundComponent, pathMatch: "full" }
];
Explanation:
It will redirect from example.com
to example.com/home
. That way the routerLinkActive
will properly highlight the selected route.
Take a look at, Angular Scaffolding. It has been done the same way. Try removing the path and you'll see.
Or even better, listen to route events:
Something Along the lines of this:
constructor(
private router: Router
) {
router.events.subscribe((event: RouterEvent) => {
this.navigationInterceptor(event);
});
}
And then do this
navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
this.currentUrl = event.url;
const route: Route = this.currentUrl;
this.loading = true;
} else if (
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError
) {
this.loading = false;
}
}
Then use the route url in template, something like this
<a mat-tab-link matFocus="true" *ngFor="let route of routes" [routerLink]="route.url" routerLinkActive [active]="currentUrl === route.url" (click)="currentUrl = route.url" #tabs>
{{route.label | uppercase}}
</a>
Take a look at the source code for better understanding

Abhijit Kar ツ
- 1,732
- 1
- 11
- 24
-
Yes, redirect is an option, but what if I don't want redirect? – Jaume Sastre Mar 17 '18 at 19:09
-
@JaumeSastre I have the solution, let me update the answer – Abhijit Kar ツ Mar 17 '18 at 19:10