Angular

Routing & Navigation with Angular's Router

PRO

Lets create the two components that our router module is configured to load: the ProfileComponent and the HomeComponent:

app/profile/profile.component.html

<div>This is Joe's profile</div>

app/home/home.component.html

<div>This is the home page.</div>

app/app.component.html

<nav>
  <a routerLink="/profile">Profile</a>
  <a routerLink="/home">Home</a>
</nav>
<router-outlet></router-outlet>

The routerLink attributes above indicate that the desired destinations are static in nature. You might include routerLinks of this type in your application's main navigation.

When you run into scenarios when your destinations are dynamic, you can use the [routerLink] directive.

<h2>HEROES</h2>
<ul class="heroes">
  <li
    *ngFor="let hero of heroes$ | async"
    [class.selected]="hero.id === selectedId"
  >
    <a [routerLink]="['/hero', hero.id]">
      <span class="badge">{{ hero.id }}</span>{{ hero.name }}
    </a>
  </li>
</ul>

<button routerLink="/sidekicks">Go to sidekicks</button>

The more important thing to note is that we created a link (<a [routerLink]="['/hero', hero.id]">) that appears to be an array. This is actually how you link around to things in Angular dynamically. Instead of the ugly way of linking in AngularJS where dropped variables into strings, the array syntax in Angular allows you to pop variables in and every new array element automatically receives it's own slash before it (i.e. ['/hero', hero.id] with a hero.id value equal to 99 becomes /hero/99). This syntax makes it substanstially easier to link to dynamically generated routes.

You can view the working source code here:

And now when you click the link in the HomeComponent, the page now displays the contents of the ProfileComponent thanks to the router!

 

I finished! On to the next chapter