To manage redirection in your routing module, you can use a redirect.
const routes: Routes = [
{ path: "", redirectTo: "home", pathMatch: "full" },
{ path: "**", component: PageNotFoundComponent, pathMatch: "full" }
];
Here's the explanation:
The redirect will send users from example.com
to example.com/home
. This way, the routerLinkActive
will appropriately highlight the selected route.
Check out Angular Scaffolding for a demonstration of this method. Try removing the path and observe the difference.
A more effective approach is to monitor route events:
View Demo
Access Source Code
Consider implementing something like this:
constructor(
private router: Router
) {
router.events.subscribe((event: RouterEvent) => {
this.navigationInterceptor(event);
});
}
Follow up by implementing this logic:
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;
}
}
Utilize the route URL within your template, similar to this example:
<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>
Review the source code for further clarity on implementation.