Angular 4 Routing and Navigation Tutorial

Angular 4 Routing and Navigation Example

Angular 4 Routing Example

In Angular 2 and Angular 4 you can navigation between pages without the need of reloading the whole page.

Angular 4 Router

By using Angular router you can move from one page to another without reloading the whole page.

Angular 4 Router Example

In the following example i will create a page with two links, each link will change the content of the page without going to a different url.

I started by creating a new Angular 4 project, in Angular 4 structure there is a main component which i will add the links to it 'ex.: about and news' links.

Create Pages Components

Now i will start by creating 2 components, one for the about page and the other for the news.

Create 2 Components

I added some content to each of the components html files:

news.component.html

<p>
This is the News page content
</p>

 

about.component.html

<p>
This is the About page content
</p>

 

Import Router

First we need to import the router module into the main app module and the routes.

app.module.ts

RouterModule -- The module which is responsible for navigation.
Routes -- This will be an array which includes all the routes  of information of each page.

import { RouterModule, Routes } from '@angular/router';

Then i am going to add both the RouterModule and define inside it all the routes of the page we will create.

Add RouterModule into the import then define the routes by adding forRoot() function and inside it's array define  the pages like the below example:

Imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{path: 'about', component: AboutComponent},
{path: 'news', component: NewsComponent},
])
],

Explanations:

  • forRoot -- Is the function to define all the pages.
  • Inside the forRoot function create an array with objects for each route 'page'.
  • Each object will have a path which will be called whenever the hyperlink is called and a component which is the name of the class which loaded from the component.ts

Add links to the main component

app.component.html

Below links will correspond to the RouterModule.forRoot were defined earlier.

<a routerLink="/news">News</a>
<a routerLink="/about">About</a>

When clicking on any of the above links the page needs to know where to load the pages, for this you need to create router-outlet tags like below example.

<router-outlet></router-outlet>

This tutorial code is available on github.


Subscribe to
for video tutorials updates