Simple Routing in Angular 2


Routing and Router

Angular 2 app can be divided into several views that you can navigate between through routing. 
Routing allows you to route to different components based on the url on the browser or url given through a link.

Prerequisites

Angular Cli must be installed if not installed check out my previous article “Install and run Angular 2 apps using Angular CLI”. Some basic knowledge on Html, Css, Javascript, Oops.

Create Routers

Create two simple components and route between them using our routing. Here we created school maintenance app which has two components student details and staff details. for component creation check my another article “Simple Component in Angular 2

app.component.html

There are three main components that we use to configure routing in Angular:

Routes describes our application’s routes
RouterOutlet is a “placeholder” component that gets expanded to each route’s content
RouterLink is used to link to routes

app.module.ts

Analyzing app.module.ts

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

Imported RouterModule, Routes to app.module.ts to config and apply routing in our app.

const appRoutes: Routes = [
 { path: ‘student’, component: StudentComponent },
 { path: ‘staff’, component: StaffComponent },
];

appRoutes route object holds the routing configuration details.

path — to specify the URL
component — To specify the component we want to route to
redirectTo — we can redirect using the redirectTo option

RouterModule.forRoot(appRoutes)Import and to supply our configuration(appRoutes) router object to RouterOutlet and RouterLink components in RouterModule module.

Thank you!!! Happy Coding.