In this article, we are going to learn how to implement routing in Angular 2 with example.
Routing is a concept which helps users to navigate from one view to another view of the application. Similarly, routing in Angular 2 helps users to navigate from one view to another view depending upon the URL which user enters in the browser. In component based architecture of Angular 2, Angular looks into the routes array, match the path as per the route requested and loads the component relevant to the requested route as well as makes available the relevant data for that particular route.
So, let’s look into some core concepts of Angular 2 routing step by step implementation below. Here I am using the same “StudentList” example which I have used in my previous articles so far. You can download the latest code from here.
Step 1. Route Configurations
Base RefFirst thing we need to add the base tag to the index.html file in the root folder src/index.html.
- <base href="/src/">
Import Modules
We need to import two modules from ‘@angular/router’ library package for implementing the routing -
- import { Routes, RouterModule } from '@angular/router';
Routes
The Routes is an array of routes objects defined for the Angular application. We need to make an array of Routes type and add the route objects inside the array. As route object, we set up the path and the components which we want to use for that particular path.
- export const routes: Routes = [
- { path: '', redirectTo: 'list-student', pathMatch: 'full' },
- { path: 'list-student', component: StudentListComponent },
- { path: 'course-list', component: CourseComponent }
- ];
Each route has many properties. Some of those properties are –
- Path – URL to be shown in the browser.
- Component – Component to be load when the application is on specific route.
- RedirectTo – Configure the route redirect to another route
- PathMatch – PathMatch property tells Angular how it should match the URL provided in order to redirect to specific route.
- Children – Tell the Angular about the child route objects on that particular route.
To implement the routing in Angular 2, we need to import the router’s module into our application module to register the route objects. That is called RouterModule. To provide information about our routes or components or we can say like to define our route config, Angular RouteModule provides us two static methods –
- forRoot
This is used when defining the route config for our application in our main module.- export const routing = RouterModule.forRoot(routes);
- forChild
This is used for our featured/child modules rather than our main module and very similar to forRoot method. This is mainly used when we don’t allow to configure our all routes in only main (root) module. Instead, we allow our other modules to configure routes for themselves, which will be import into our main module if needed.- export const routingCourses = RouterModule.forRoot(courseRoutes);
Let’s take a look at code configuration together, and how we’d use this,
app.routes.ts
In src/app/app.routes.ts file, we imported routing modules for implementing routing, imported “StudentList” component as well as “CourseComponent”, created routes config with path and component properties and register it with forRoot method of RouterModule. Look at the highlighted lines below,
- import { Routes, RouterModule } from '@angular/router';
- import { StudentListComponent } from './student/student.component';
- import { CourseComponent } from './course/course.component';
- export const routes: Routes = [
- { path: '', redirectTo: 'list-student', pathMatch: 'full' },
- { path: 'list-student', component: StudentListComponent },
- { path: 'course-list', component: CourseComponent }
- ];
- export const routing = RouterModule.forRoot(routes);
Note
When our application will start, it will navigate to the empty route by default. We configured the router to redirect to a “list-student” route by default using “redirectTo” property.
app.component.ts
In src/app/app.component.ts file, we imported our routing module (which we created above) inside our main application module. Look at the highlighted lines below,
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { routing } from './app.routes';
- import { AppComponent } from './app.component';
- import { StudentListComponent } from './student/student.component';
- import { courseCategoryPipe } from './student/student.coursepipe';
- import { SearchBarComponent } from './Shared/SearchBar/searchbar.component';
- import { CourseComponent } from './course/course.component';
- @NgModule({
- imports: [BrowserModule, routing],
- declarations: [AppComponent, StudentListComponent, courseCategoryPipe, SearchBarComponent, CourseComponent],
- bootstrap: [ AppComponent ]
- })
- export class AppModule { }
Step 2. Displaying Routes
Router-OutletOnce routes configuration is done, now we need to tell Angular where the components will be loaded. This is done by using a directive “router-outlet”. When the router matches the route and found the component to be load, it will dynamically inject the component inside the router-outlet directive.
- <router-outlet></router-outlet>
RouterLink
To create links to the routes, we use “routerLink” directive in Angular 2 routing like below,
- <a routerLink="/list-student">Student List</a>
Navigating Programmatically
To navigate programmatically to a route, we use navigate function in Angular 2 like below –
- this.router.navigate(['/course-list']);



vish GPosted Apr 3, 2018, 8:49 AM
Hello Rahul, Your blog on Angular2 is very insightful and knowledge gaining. Here, I would like to take this moment to check on how can I develop button functionality in angular(scenario is I want to display a button upon radio button selection) Could you please guide me in achieving this scenario.