Using the <router-outlet> in components other than the application component?

11,379

The <router-outlet> is not linked to the component. It is linked to the child routes of the component to which it resides.

A routerLink just navigates the Applications assigned routes

For example suppose you have these routes

const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'account', component: AccountComponent, children: [
    { path: 'details', component: AccountDetails
  ]
];

Your AppComponent looks something like this we'll say

@Component({
  template: `
<div>
  <a routerLink='/home'>Home</a>
  <a routerLink='/account'>Account</a>
  <a routerLink-'/account/details>Account Details</a>
</div>
<div>
  <router-outlet></router-outlet>
</div>
`
})

Let's say your AccountComponent is something like this

@Component({
  template: `
    <div>
      Account Name {{ name }}
    </div>
    <div>
      <a routerLink='/home'>Home</a>
      <a routerLink='/account'>Account</a>
      <a routerLink-'/account/details>Account Details</a>
    </div>
    <router-outlet></router-outlet>
    `
  })

When you click on Account Details, it will load the account component with the details in the router-outlet of the account component.

When you click on home it will load the app component with the home component loaded in the router-outlet of that component. It loads the component in the router-outlet based on where it sites in the route tree.

Note: This is not production code and should not be used as such.

Share:
11,379
Ole
Author by

Ole

Updated on June 21, 2022

Comments

  • Ole
    Ole almost 2 years

    If we use the <router-outlet> in a component (Any component) and then put a routerLink to another component within that component, does the link always render the component linked to in the <router-outlet> of the currently active component?

    In other words are component routerLink attributes always paired with the <router-outlet> within a component?