简体   繁体   中英

How can I link to a route to two components in Angular 2+?

My application looks like (a bit simplistic):

<root-component>
  <div id="header>
    <header-component>
      Here are top menu items and some block (cashbox and etc).
      Depend on the route.
      Frequently one header component can be shown on many routes.
    </header-component>
    <right-menu-component>
      Here is right menu (in the right corner). Did not depend on route, always shown.
    </right-menu-component>
  </div>
  <div id="content">
     <content-component>
       Here are all content, business logic. Depend on route.
     </content-component>
  </div>
</root-component>

About how I see the solution (it doesn't work)

const routes: Routes = [
  { path: 'orders', components: 
    [
      {selector: 'header-component', component: 'OrdersHeader'},
      {selector: 'content-component', component: 'OrdersComponent'}
    ]
  },
  { path: 'order-editor', components: 
    [
      {selector: 'header-component', component: 'OrdersHeader'},
      {selector: 'content-component', component: 'OrderEditorComponent'}
    ]
  },
  { path: 'some-report', components: 
    [
      {selector: 'header-component', component: 'ReportsHeader'},
      {selector: 'content-component', component: 'ReportsComponent'}
    ]
  }...

I want to link to header and content components to one route. I cannot put one into the other because between them is right menu and because the layout will be break.

How to solve this problem?

You can use a named outlet to change header and content routes independently of each other, eg content as default (unnamed) outlet and header in a named outlet:

<router-outlet name="header"></router-outlet>
                     ^^^^^^
const routes: Routes = [
  { 
    ...
    { path: 'header-a', component: HeaderAComponent, outlet: 'header' },
                                                              ^^^^^^
  }

For further information, see the docs: Displaying multiple routes in named outlets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM