Home > Net >  Split routed component to two outlets
Split routed component to two outlets

Time:10-09

I'm wondering if is possible to split component to two router outlets? For example, I have two not nested router outlets:

<router-outlet></router-outlet>  
<router-outlet name="second"></router-outlet> 

, route with specific component, which contains:

<div #a></div>
<div #b></div>

And after navigating to path div#A goes to <router-outlet> while div#B goes to <router-outlet name="second">.

Or maybe there is better way of passing some HTML data to component, which lays outside <router-outlet>?

Thanks.

CodePudding user response:

If you want to split the content between two router-outlets you will need to decompose your template into two separate components, and then setup your routes for using named router outlets.

Example


const routes: Routes = [
  {
    path: 'view',
    component: OutletAComponent,
    outlet: 'a',
  },
  {
    path: 'view',
    component: OutletBComponent,
    outlet: 'b',
  },
];

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

Next we need a component which hosts our two router-outlets

  <!-- app.component.html -->
  <a [routerLink]="[{ outlets: { a: ['view'], b: ['view'] } }]">Go to view</a>
  <router-outlet name="a"></router-outlet>
  <router-outlet name="b"></router-outlet>

Note, the routes do not necessarily need to be the same, in this case view was just chosen for both to illustrate how you would setup a router outlet with two routes.

The important aspect is merely to understand that the outlets prop has key values which must match with the desired router-outlet name, and the accompanying value will be the desired route.

See Stackblitz: https://stackblitz.com/edit/angular-ivy-vvdvtc

  • Related