Routing & Navigation with Angular's Router


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


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


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


  <a routerLink="/profile">Profile</a>
  <a routerLink="/home">Home</a>

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.

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

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

The more important thing to note is that we created a link (<a [routerLink]="['/hero',]">) 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',] with a 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