Parth Agarwal
Parth Agarwal

Reputation: 137

Why isn't the child route working in angular?

Here is the relevant code for the routing module ts file:

    const routes: Routes = [{
        path: '',
        component: LoginPageComponent
      },
      {
        path: 'dashboard',
        component: DashboardPageComponent
      },
      {
        path: 'dashboard/:id',
        component: DashboardPageComponent,
        children: [{
          path: 'home',
          component: HomeComponent
        }]
      },
      {
        path: '**',
        component: LoginPageComponent
      },
    ];

Here is my dashboard component:

<app-sidenav></app-sidenav>
<app-bar></app-bar>
<router-outlet></router-outlet>

When I navigate to the dashboard/home directly, the HomeComponent does not load. Why is this?

Note: I tried removing the :id.

Upvotes: 0

Views: 98

Answers (3)

SiddAjmera
SiddAjmera

Reputation: 39432

I'd like to add that there are a few issues with your Route Config that you can fix:

const routes: Routes = [{
    path: 'login',
    component: LoginPageComponent
  },
  {
    path: 'dashboard',
    component: DashboardPageComponent,
    children: [{
      path: 'home',
      component: HomeComponent
    }]
  },
  {
    path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  },
  {
    path: '**',
    component: LoginPageComponent
  },
];

Also, you're loading the same component DashboardPageComponent on /dashboard and /dashboard/:id. Consider defining a specific Component for /dashboard/:id

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

Since you have defined home route inside dashboard/id segment, you can not directly access /home by doing dashboard/home, because this pattern will not match any of routing definition.

You must specify parent segment dashboard/id before accessing child segment /home route). All together mention dashboard/someid/home as it will try to match whole URL dashboard/someid/home with registered route definition, and out of which inital dashboard/someid pattern will match and it will render UserDashboardPageComponent later it tries to search for remaining pattern /home which matches with the /home child path, accordingly it will help render HomeComponent inside router-outlet of UserDashboardPageComponent component

Upvotes: 2

Developer
Developer

Reputation: 169

Your path for home component isn't right. Removing :id from path: 'dashboard/:id' works fine.

I've created a demo here

Upvotes: 1

Related Questions