Dynamically Adding Route Components

Rather than define each route's component separately, use RouterOutlet which serves as a component placeholder; Angular dynamically adds the component for the route being activated into the <router-outlet></router-outlet> element.

  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app',
  4. template: `
  5. <nav>
  6. <a routerLink="/component-one">Component One</a>
  7. <a routerLink="/component-two">Component Two</a>
  8. </nav>
  9. <router-outlet></router-outlet>
  10. <!-- Route components are added by router here -->
  11. `
  12. })
  13. export class AppComponent {}

In the above example, the component corresponding to the route specified will be placed after the <router-outlet></router-outlet> element when the link is clicked.

View Example

View examples running in full screen mode to see route changes in the URL.

原文: https://angular-2-training-book.rangle.io/handout/routing/routeroutlet.html