Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Using the Angular 5 Router (Tutorial)

By Gary simon - Nov 04, 2017

Ready to build Awesome Angular Apps?

A Free Course, Free Tutorials and Full App Development Courses!

Great! Check your email

I've just sent you the first email to get you started.

The following tutorial is a part of our 100% free course Learn Angular 5 from Scratch - Angular 5 Tutorial

So far in this course, we've created a couple components but we've only worked within one. Right now, if you click on the about link in the simple navigation, it will error.

We can use the Angular 5 router to specify which comopnent should load by default when the app is loaded, and also utilize the <router-outlet>.

Let's get started..

If you prefer watching a video instead..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.

Working in the App Routing File

When we started this project with the Angular CLI, we used the --routing flag, which set us up with a file located at /src/app/app-routing.module.ts, visit this file and import the 2 components we created earlier:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';     // Add this
import { AboutComponent } from './about/about.component';  // Add this

Next, within the routes constant, update it to the following:

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'about',
    component: AboutComponent
  }
];

This will set the default path when the app loads to show the HomeComponent wherever the <router-outlet> is placed.

Then, the path of /about will show the AboutComponent.

Next, visit app.component.html and delete the <app-home></app-home> selector element, as we don't need it anymore:

<ul>
  <li><a routerLink="">Home</a></li>
  <li><a routerLink="about">About</a></li>
</ul>

<router-outlet></router-outlet>

Note: I also updated the home RouterLink to be empty.

Now, if you visit the browser and click back and forth between our two navigation links, it will display the appropriate components!

Setting and Fetching Angular 5 Route Parameters

While we don't need any type of query parameters for our particular project, we're going to create one just so that I can show you how you can work in parameters to your URL's and retrieve the values if need be.

Visit app-routing.module.ts and make the following changes:

  {
    path: 'about/:id',             // Add /:id here
    component: AboutComponent
  }

This is designating that anything after about/ will be referred to as id, which is a route parameter. You can, of course, create multiple parameters within a single URL as such: about/:id/:whatever.

Visit the app.component.html file and change the following:

  <li><a routerLink="about/48">About</a></li>

We're choosing a random ID value here for the id parameter. In the context of a real application, this would likely be the ID associated with information pulled from a database.

Visit about.component.ts and import ActivatedRoute:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';      // Add this

This will give us access to the route parameters.

Next, we have to create an instance of ActivatedRoute through dependency injection, which is done in the constructor of the class:

export class AboutComponent implements OnInit {
  
  constructor(private route: ActivatedRoute) { 
    this.route.params.subscribe(res => console.log(res.id));
  }

  ngOnInit() {
  }

}

Inside of the constructor, we're subscribing to the router parameters, and console logging the result.id.

If you save this and visit the /about/48 URL, and hit CTRL-SHIFT-I to bring up the inspector and console log, you will see it shows a 48!

In a real world context, instead of console logging, you would create a property and bind the res.id to that property and use it as needed.

Component Router Navigation

Sometimes, you may need to change the router outlet component based on logic occurring in a component class.

In this case, let's import the Router from the angular/router within our about.component.ts file:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';             // Add this

Once again, we create an instance of it through dependency injection:

constructor(private route: ActivatedRoute, private router: Router) { 

Let's create a method that will call the router path of home (we're leaving it empty, as it is in the app-routing.module.ts file:

  sendMeHome() {
    this.router.navigate(['']);
  }

Next, open up about.component.html and update the HTML to:

<p>
  This is what I'm all about. <a href="" (click)="sendMeHome()"><strong>Take me back</strong></a>.
</p>

Save it, and click on Take me back -- You've now used your component logic to send users to a new path.

Going Forward

Wow, you've learned a lot so far if you've been following from the beginning! 

In the next lesson, we're going to take a look at creating services in Angular 5.


Share this post




Say something about this awesome post!