Angular 4/5/6 Router Simple Example & Demo
Angular 4 Router Simple Example & Demo:
Router is one of the great feature available in angular to bring the content without refreshing the page. Here we are going to have three links namely home, login and register. On click of each link a new content will be displayed only in that particular area without refreshing the full page.
Table of Contents
Prerequisite:
Node JS, NPM and Angular-CLI must be installed and running on your machine.
If you do not know how to install, refer the below links for quick understanding and installation guide:
Hope you have proper setup now. Let’s move on to router example.
Download Project From Github:
Video Tutorial:
Step 1: Create a new angular-cli project
Step 2: Now generate home, login and register components inside app folder
comments:
ng g component home
ng g component login
ng g component register
Step 3: Add Required Modules in app.module.ts
import { RouterModule, Routes } from ‘@angular/router’;
Add the routing paths,
const routes: Routes =[
{
path: ‘home’, component: HomeComponent
},
{
path: ‘register’, component: RegisterComponent
},
{
path: ‘login’, component: LoginComponent
}
Add the routes and RouterModule to import statement:
RouterModule.forRoot(routes)
Full app.module.ts file for your reference:
[html]
import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { FormsModule } from ‘@angular/forms’;
import { HttpModule } from ‘@angular/http’;
import { RouterModule, Routes } from ‘@angular/router’;
import { AppComponent } from ‘./app.component’;
import { HomeComponent } from ‘./home/home.component’;
import { LoginComponent } from ‘./login/login.component’;
import { RegisterComponent } from ‘./register/register.component’;
const routes: Routes =[
{
path: ‘home’, component: HomeComponent
},
{
path: ‘register’, component: RegisterComponent
},
{
path: ‘login’, component: LoginComponent
}
]
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
RegisterComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
[/html]
Step 4: Add the navigational links in app.comonent.html
[html]
<h1>
{{title}}
</h1>
<a routerLink=”/login”>Login</a>
<a routerLink=”/home”>Home</a>
<a routerLink=”/register”>Register</a>
<router-outlet></router-outlet>
[/html]
<router-outlet></router-outlet> is the place where it displays the content of login/home/register links.
Step 5: Verify the output