Ang2
Routing & Navigation with Angular 2's Router
  •  

Linking & Navigating Between Components

PRO

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

app/profile.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'Profile-page',
  template: `
  <div>This is Eric's profile</div>
  `
})
export class ProfileComponent {
  constructor() {}

}

app/home.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'home-page',
  template: `
  <div>This is the home page. Go to <a [routerLink]="['profile']">eric's profile</a></div>
  `
})
export class HomeComponent {
  constructor() {}

}

You'll notice that the template shown here is written inline using the ES6 template literal syntax (which allows you to write multiline strings in Javascript files). Since the template is defined inline, we declare it with the template attribute instead of templateurl (which is very similar to how things worked in Angular 1).

The more important thing to note is that we created a link (<a [routerLink]="['profile']">eric's profile</a>) that appears to be an array. This is actually how you link around to things in Angular 2. Instead of the ugly way of linking in Angular 1 where dropped variables into strings, the array syntax in Angular 2 allows you to pop variables in and every new array element automatically receives it's own slash before it (i.e. ['profile', 'eric'] becomes /profile/eric). 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