Search code examples
angularangular-routerlink

routerLink not navigating as expected


I have the following routes

import { Routes } from '@angular/router';
import { DashboardComponent } from './pages/dashboard/dashboard.component';
import { TeamsComponent } from './pages/teams/teams.component';
import { LoginComponent } from './pages/login/login.component';
import { BaseLayoutComponent } from './base-layout/base-layout.component';

export const routes: Routes = [
    { path: 'login', component: LoginComponent },
    {
        path: '',
        component: BaseLayoutComponent,
        children: [
            { path: '', component: DashboardComponent, pathMatch: 'full' },
            { path: 'dashboard', component: DashboardComponent },
            { path: 'teams', component: TeamsComponent }
        ]
    },

    { path: '**', redirectTo: 'dashboard' }
];

I have the following routerLink, which is part of my side menu navigation

<a routerLink="/teams" routerLinkActive="active">Teams</a>

further down the page I have the following

 <main class="py-10">
            <div class="px-4 sm:px-6 lg:px-8">
                <router-outlet />
            </div>
        </main>

When trying to click on Teams, it doesn't appear clickable, when adding a (click)="teamsClicked()" I can write to the console, so I'm not sure what I'm doing here but it seems the router isn't working as expected, can anyone spot any issue here?

BaseLayoutComponent

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-base-layout',
  imports: [RouterOutlet],
  templateUrl: './base-layout.component.html',
  styleUrl: './base-layout.component.css'
})
export class BaseLayoutComponent {


  onClick() {
    console.log('Team link clicked');
  }

}

Solution

  • Make sure you have router-outlet set on BaseLayoutComponent HTML.

    You can try setting the default route to the bottom.

        children: [
            { path: 'dashboard', component: DashboardComponent },
            { path: 'teams', component: TeamsComponent },
            { path: '', component: DashboardComponent, pathMatch: 'full' },
        ]
    

    On the component where you have the routerLink in HTML. Make sure you have added RouterModule to the imports array of the component.

    @Component({
      ...
      imports: [RouterModule], // <- changed here!
      standalone: true,
      ...
    })
    export class BaseLayoutComponent {