Search code examples
angularangular-routingrouter-outlet

Angular 2+ - modal component rendered always at same place


I'm currently solving quite tricky problem. I would like to have in my root app.component.html place, where will be rendered modal window, but I would like to use named router-routlets as well to have this modal available through URL.

My router array looks like:

const routes: Routes = [
  { path: '', redirectTo: '/admin/orders', pathMatch: 'full' },
  {
    path: 'admin/orders',
    component: OrdersComponent,
    canActivate: [AuthGuard],
    children: [
      { path: '', component: OrderListComponent },
      {
        path: ':id',
        component: OrderDetailComponent,
        outlet: 'modal'
      }
    ]
  },
  { path: 'admin/stats', canActivate: [AuthGuard], component: StatsComponent },
  { path: 'admin/settings', canActivate: [AuthGuard], component: SettingsComponent },
  { path: 'admin/user', canActivate: [AuthGuard], component: UserComponent },
  { path: 'auth', component: AuthComponent }
];

So challenge is to render OrderDetailComponent somehow here into app.component.html:

<div class="app">
  <app-navigation></app-navigation>
  <app-header></app-header>
  <main class="app__content">
    <router-outlet></router-outlet>
  </main>
  <!-- HERE I WANT TO RENDER MODAL CONTENT -->
</div>

Of course one way to solve this is to have another route path of OrdersComponent like this:

  {
    path: 'admin/orders',
    component: OrdersComponent,
    canActivate: [AuthGuard],
    outlet: 'modal',
    children: [
      {
        path: ':id',
        component: OrderDetailComponent,
      }
    ]
  }

and then in app.component.html:

<div class="app">
  <app-navigation></app-navigation>
  <app-header></app-header>
  <main class="app__content">
    <router-outlet></router-outlet>
  </main>
  <router-outlet name="modal"></router-outlet>
</div>

But the problem here is that it will call me twice AuthGuard.

I would appreciate any suggestion which will lead me how to solve this correctly.

Thanks


Solution

  • Will doing the following not solve it?

    <div class="app">
      <app-navigation></app-navigation>
      <app-header></app-header>
      <main class="app__content">
        <router-outlet></router-outlet>
      </main>
      <app-order-detail></app-order-detail>
    </div>
    

    Then use *ngIf to render the component based on whatever condition is relevant.