Angular 2 Routing

Angular 2 Routing

Angular 2 Routing is used to navigate from one view to another view.  to navigate from one page to another page Angular has given Router Component which is highly configurable and feature packed router.

Angular Router is not part of the Angular core library it is in its own library package, @angular/router. So you have to import RouterModule and Router component before using it.

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

Angular 2 Routing Basics

Routes is an array type that defines the routing for the application. This is where we can write the routing paths.

Each Route will have different attributes like

  1. path – URL that you want to show in browser.
  2. component – Angular Component that you want to be rendered when given path matched in browser.
  3. redirectTo – Used to redirect route, We can not use component and redirectTo in same path. Each route can have either component or redirect attribute.
  4. pathMatch – By using pathMatch we can route our component base on some given parameter like pathMatch: 'full' means, that the whole URL path needs to match then only Angular Router will route the component. pathMatch: 'prefix' means, the first route where the path matches the start of the URL is choosen
  5. children – used to render child component. Mostly used in tabbed navigation.

The first and important step that you need to follow is base URL tag must be set within the <head> tag inside index.html.

<base href="/">

To use Routes, create an array of route configurations like below and RouterModule.forRoot takes the Routes array as an argument and returns to the router module.


import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [
  { path: 'component-one', component: ComponentOne },
  { path: 'component-two', component: ComponentTwo }
 export const routing = RouterModule.forRoot(routes);

And then we have to import our routing configuration in the root of our application like below.

  imports: [
  declarations: [
  bootstrap: [ AppComponent ]
export class AppModule {

Let’s go through the Angular 2 Routing types.

  1. Standard view routing,
  2. Nested Child Routing,
  3. Named Routing.
  4. Routing Parameters.

Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: Sales: +91 8085506229