beanic
beanic

Reputation: 564

Nested routes Angular

I am trying to have two levels of nested routes in my myfile.routing.module.ts file but when I try to access to the route it redirects to the home. Here is my code:

routing.module.ts

.
.
.
const routes: Routes = [
  {
    path: '',
    children: [
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      {
        path: 'home',
        component: HomeComponent,
        children: [
          { path: '', redirectTo: 'page' },
          {
            path: 'page',
            component: PageComponent,
            canActivate: [PageGuard],
          },
          {
            path: 'more', component: MoreComponent,
            children: [
              { path: '', component: MoreComponent },
              { path: 'plants', component: PlantsComponent },
              { path: 'cars', component: CarsComponent },
              { path: 'pets', component: PetsComponent },
          ]},
        ],
      },
    ],
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class myFileRoutingModule {}

in more.component.html I have added <router-outlet></router-outlet>

and in home.component.html I have the links like so:

<a [routerLink]="['home/page/more/plants']">plants</a><br />
<a [routerLink]="['home/page/more/cars']">cars</a><br />
<a [routerLink]="['home/page/more/pets']">pets</a><br />

so the problem that I have is that I can't access to each section (for example home/page/more/plants) because it redirects to home all time.

Does anyone know what's the problem?

Upvotes: 1

Views: 135

Answers (1)

Masoud Bimar
Masoud Bimar

Reputation: 7781

You don't need the first empty level,

This might fix your problem:

const routes: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    {
      path: 'home',
      component: HomeComponent,
      children: [
        { path: '', redirectTo: 'page' },
        {
          path: 'page',
          component: PageComponent,
          canActivate: [PageGuard],
        },
        {
          path: 'more', component: MoreComponent,
          children: [
            { path: '', component: MoreComponent },
            { path: 'plants', component: PlantsComponent },
            { path: 'cars', component: CarsComponent },
            { path: 'pets', component: PetsComponent },
        ]},
      ],
    }
];

Notice all component that came with children must contain <router-outlet></router-outlet> like HomeComponent & MoreComponent

Upvotes: 2

Related Questions