Use of Named Router Outlets in Angular

April 1, 2025 11:40 PM

Angular Named Router outlet

Named router outlets in Angular allow you to render multiple components in different parts of your application simultaneously, based on the current route. Instead of having a single <router-outlet> that displays one component at a time, you can have multiple outlets, each with its own name, and configure your routes to render different components in each outlet.

  1. Multiple Outlets: You can define multiple <router-outlet> elements in your template, each with a unique name.

  2. Route Configuration: You configure your routes to specify which component should be rendered in each outlet.

  3. Simultaneous Rendering: When a route is activated, Angular renders the specified components in their respective outlets simultaneously.

Let's add two router outlets

<app-header />
<main>
  <divclass="container">
    <router-outlet></router-outlet>
    <router-outletname="sidebar"></router-outlet>
  </div>
</main>


  • A primary outlet (unnamed): <router-outlet></router-outlet>
  • A named outlet: <router-outlet name="sidebar"></router-outlet>


If we are using Ng Modules then we have to use this code for the Route configurations.

constroutes:Routes=[
  { path:'', redirectTo:'/home', pathMatch:'full' },
  { path:'home', component:HomeComponent },
  { path:'login', component:LoginComponent },
  { path:'login', component:LoginComponent },
  { path:'sidebar', component:SidebarComponent, outlet:'sidebar' }
];
@NgModule({
  imports:[RouterModule.forRoot(routes)],
  exports:[RouterModule]
})
exportclassAppRoutingModule { }


If you are using latest Angular versions

constroutes:Routes=[
  { path:'', redirectTo:'/home', pathMatch:'full' },
  { path:'home', component:HomeComponent },
  { path:'login', component:LoginComponent },
  { path:'sidebar', component:SidebarComponent, outlet:'sidebar' }
];
bootstrapApplication(AppComponent, {
    providers:[provideRouter(routes)]
})
  .catch(err=>console.error(err));


Navigating to Named Outlets

To navigate to a route that uses named outlets, you can use the routerLink directive with the [routerLink] syntax:

<a [routerLink]="[{ outlets: { primary: 'login', sidebar: 'sidebar' } }]">Login with Sidebar</a>


Benefits of Named Outlets

  1. Complex Layouts: They allow you to create more complex layouts with multiple dynamic regions.

  2. Independent Content: You can load and update different parts of the page independently.

  3. Modularity: They promote a modular design by allowing you to encapsulate different parts of the UI into separate components

Named router outlets provide a powerful way to manage complex layouts in Angular applications. By using named outlets, you can render multiple components simultaneously in different parts of the page, creating a more dynamic and flexible user interface.



Comments


    Read next