@angular/router wrap route component in router-outlet for styling

Viewed 1933

I have a simple angular (8+) application using @angular/router with multiple components as routes, and each component use @angular/animations for transitions.

<router-outlet> directive is fullscreen using css width: 100vw and height: 100vh to override default scroll. My idea is to wrap each route with a <div> or a specific class which will allow to define fixed layout.

My current version works great, but I have to manually add the <div> and was hoping to find an automatic solution like @angular/animations does.

app.ts with main router

  <main [@routerTransition]="getState(o)">
    <router-outlet #o="outlet"></router-outlet>
  </main>

Route component html template

<div class="route"> <!--  class which should be automatically wrapped -->
  <div class="container">
    <h1>title</h1>
    <p>Blablabla</p>
  </div>
</div>

Routes

// State is use to bind animation
export const appRoutes: Routes = [
  {
    path: 'page1',
    loadChildren: () => import('./page1/page1.module').then(mod => mod.Page1Module),
    data: { theme: 'light' }
  },
  {
    path: 'page2',
    loadChildren: () => import('./page2/page2.module').then(mod => mod.Page2Module),
    data: { theme: 'light' }
  },
  ...
];

Like I said, this code works exactly as expectied, but having to maintain manually a certain DOM layout is not good enough.

1 Answers

Content projection will do the job. Basically you have a shell/wrapper component. And all your individual route component will project their content into this shell/wrapper.

RouteShellComponent:

<div class="route">
    <ng-content></ng-content>
</div>

RouteAComponent:

<div class="container">
    <h1>title</h1>
    <div>...</div>
</div>

main

<app-route-shell>
    <router-outlet></router-outlet>
</app-route-shell>
Related