clemtoy
clemtoy

Reputation: 1731

How to use two router outlets for same path using Angular 5

I have the following template for AppComponent:

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

I want to use this template in two cases:

I don't understand how children and named outlets works. What should be my routes in module imports?

I use Angular 5.

Upvotes: 5

Views: 2914

Answers (1)

vince
vince

Reputation: 8306

The overall approach for this is to pattern match on the route you want and give it empty child routes for each outlet.

The formatting (with brackets, curly braces, and indentation) is a bit tricky to read at a glance, so I'll isolate each route here and explain a bit...

Let's say you are at /page1:

const pageOneRoutes = {
   path: 'page1',
};

This path has two child routes (each outlet gets its own child route). Both of these children paths are the "empty" path because you want your child path to match page1 by itself:

const pageOneRoutes = {
   path: 'page1',
   children: [
     { path: '', outlet: 'menu', component: Menu1Component },
     { path: '', outlet: 'main', component: Main1Component }
   ]
};

Then you simply repeat this process for /page2 and the other components you want to load.

const pageTwoRoutes = {
   path: 'page2',
   children: [
     { path: '', outlet: 'menu', component: Menu2Component },
     { path: '', outlet: 'main', component: Main2Component }
   ]
};

For more information, check out this part of Angular's routing tutorial which uses this approach for pattern matching in child routes: https://angular.io/guide/router#child-route-configuration.


The whole thing might look something like this:

const ROUTES: Routes = [
 {
   outlet: 'primary',
   path: '',
   children: [
     {
       path: 'page1',
       children: [
         { 
           path: '',
           outlet: 'menu',
           component: Menu1Component
         },
         {
           path: '',
           outlet: 'main',
           component: Main1Component
         }
      },
      {
        path: 'page2',
        children: [
          { 
           path: '',
           outlet: 'menu',
           component: Menu2Component
          },
          {
           path: '',
           outlet: 'main',
           component: Main2Component
          }
        ]
      }
     ]
   ]
 } 
]

Upvotes: 12

Related Questions