Search code examples
angularangular-routingangular-router

Auxiliary routes not showing component


I am trying to implement auxiliary routing in my angular app, but for some reason the component is not shown, even though that the url in the browser changes.

My routes module looks like that:

const routes: Routes = [
    { path: 'students', canActivate: [AuthGuard], component: StudentsComponent, outlet: 'main' },
    { path: 'login', component: LoginComponent },
    { path: '', canActivate: [AuthGuard], component: HomeComponent }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

The HTML template of the HomeComponent essentially boils down to:

<router-outlet></router-outlet>

<div class="">
    <button [routerLink]="[{outlets: {main: ['students'] } }]">aux route</button>

<!-- <button [routerLink]="[{outlets: {main: ['/students'] } }]">aux route</button>
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '%2Fevents' -->

    <router-outlet name="main"></router-outlet>
</div>

So, basically when I open http://localhost:4200 in the browser, I can see my aux button and when I click it, the url in the browser changes to: http://localhost:4200/(main:students)

It looks fine, but the StudentComponent is never shown on the page.

I wonder what I do wrong...

The StudentComponent just displays the default:

<p>StudentComponent works!</p>

EDIT: I am adding a link to stackblitz that shows the problem. Please notice how the content of the third component is never shown.


Solution

  • Here is a modified version of your stackblitz, which appears to work with these routes:

    const appRoutes: Routes = [
      { path: '', redirectTo: '/home', pathMatch: 'full' },
      { path: 'home', component: HomeComponent },
      { path: 'first', component: FirstComponent },
      {
        path: 'second', component: SecondComponent,
        children: [
          {
            path: 'third',
            component: ThirdComponent,
            outlet: 'third'
          }
        ]
      },
    ];
    

    and the following template for the second component:

    <a [routerLink]="[{ outlets: { third: ['third'] } }]">Aux third component</a>
    
    <router-outlet name="third"></router-outlet>