Search code examples
angularangular-routingangular-router

Angular router-outlet for /admin route


Hi I am quite new to an Angular and I am trying to build web page that consists of multiple routes.

I want to build an admin dashboard that could be accessible from /admin url. When I access /admin I would like to display only AdminPageComponent and not the header and footer component from app.component.html that I use for all other urls. I was trying to resolve this with multiple router-outlets but I couldn't find a solution that would work in a way I want. Is there any good solution I could use for my situation ?

 { path: '', component: HomePageComponent },
 { path: 'hockey', component: HockeyPageComponent },
 { path: 'football', component: FootballPageComponent },
 { path: 'tennis', component: TennisPageComponent },
 { path: 'other', component: OtherPageComponent },
 { path: 'stats', component: StatsPageComponent },
 { path: 'results', component: ResultsPageComponent },
 { path: 'login', component: LoginPageComponent },
 { path: 'articles/:id', component: ArticlePageComponent},
 { path: 'register', component: RegisterPageComponent},
 { path: 'admin', component: AdminPageComponent},
 { path: '**', redirectTo: ''} 

My app.component.html looks like this:

<app-navigation></app-navigation>

<main role="main">

  <div class="row">
    <div class="col-xl-2 col-lg-2 col-md-2 col-sm-2 reklama">
      <p>Reklama left</p>
    </div>

    <div class="col-xl-8 col-lg-8 col-md-8 col-sm-8 col-12">
      <router-outlet></router-outlet>
    </div>

    <div class="col-xl-2 col-lg-2 col-md-2 col-sm-2 reklama">
      <p>Reklama right</p>
    </div>
  </div>
</main>

<app-footer></app-footer>

Solution

  • Your AppComponent should contain only content that is shared among ALL your components. If there is no shared content among all components the HTML of AppComponent should be <router-outlet></router-outlet>. You can then add child routes to your routing module that add the different shared portions of your application.

    For example a MainWrapperComponent and AdminWrapperComponent with their own router outlets surrounded by each section's shared HTML.

    In your routing module you can then set up a structure like this:

    const routes = [
     // This component defines the shared main content around a router outlet.
     { path: '', component: MainWrapperComponent, children: [
         // This component is a main page
         { path: 'home', component: HomeComponent}
       ]
     },
     // This component defines the shared admin content around a router outlet.
     { path: 'admin', component: AdminWrapperComponent, children: [
         // This component is an admin page
         { path: 'home', component: AdminHomeComponent}
       ]
     }
    ]