Angular Routing Simplified

Routing is all about navigation. In this blog we will understand how navigation is implemented using the Angular router.

The Angular Router follows the model of, how navigation in a browser works based on the URL. On the same lines, the router uses the browser URL as an instruction to navigate to a client-generated view. With the help of parameters to the supporting view component it decides what specific content to be presented in the view.

The router can be bound to

  • links on a page
  • different actions like button click and be handled to navigate to the appropriate application view in response to the action.

And all this activity is logged in the browser’s history journal, so that the back and forward buttons work as well.

Let’s see how this is done in Angular code.

I will take an example of an application which shows all news items as stories. The user can register and he/she will be shown stories based on his interest.

Start the basic flow

  • We should add a <base> element to the index.html as the first child in the <head> tag to tell the router how to start composing the navigation URLs.

For most cases, the app folder is the application root, so we will include the below code in index.html.

<base href="/">

Define the routes

  • Next we need to define the routes. First put down the flow  of your application between the different components. In my example, I am defining below routes mapped to Components.
  1. Default path or Landing page -> AllStories
  2. Other paths -> Login, StoryDetail
  3. Error path -> NoSite

I have broadly  listed the routes which we intend to define in our News application.

Let’s assume the components are already defined to only focus on routing here.

A new file app-routing.module.ts is created to define the routes of the application in a separate RoutingModule. This can also be directly included in app-module if the application is a very simple one, but in most applications, this is the better way to approach Routing.

  • First we import the required files to achieve this
import { NgModule } from '@angular/core';
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
  • We also import the required components.
  • Then we define the routes and the RoutingModule as below
export const appRoutes: Routes = [
   { path: '',   redirectTo: '/allstories', pathMatch: 'full' }, // default route using redirectTo
   { path: 'allstories', component: Allstories' },
   { path: 'login',  component: Login},
   { path: 'StoryDetail',  component: StoryDetail},
   { path: '**',  component: NoSite } // If no route matches, wild card or error route
  ];
export const appRoutingProviders: any[] = [
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
@NgModule({
  imports: [RouterModule.forRoot(appRoutes,{useHash: false})],
  exports: [RouterModule]
})
export class AppRoutingModule { }

The order of the routes is very important and the fallback route ‘**’ should always be the last route in the definitions.

This completes the route module definition in app-routing.module.ts.

Inclusion of Routes in AppModule

  • Next we need to import the routes in app.module.ts
import { AppRoutingModule,
      appRoutingProviders }  from './app.routing';
  • Include the AppRoutingModule in the imports for the Module
@NgModule({
  declarations: [
 AppComponent,
 Login,
 Allstories,
 StoryDetail  ],
  imports: [
 BrowserModule,
 FormsModule,
 HttpModule,
 AppRoutingModule
  ],
  providers: [
 APP_PROVIDERS,
 UserService,
 SkillService,
 appRoutingProviders,
 {provide: LocationStrategy, useClass: HashLocationStrategy},
 { provide: APP_BASE_HREF, useValue: '!' }],
  bootstrap: [AppComponent]
})
export class AppModule { }

This completes the definition and configuration of the routes.

Router Outlet

Now we have to establish an outlet for the route. This can be included in the specific component where the route starts or in the AppComponent as shown below. The view/template definition should include the router outlet as below:

@Component({
selector: 'app-root',
template: `
<main>
<router-outlet></router-outlet>
</main>
`
})
export class AppComponent {
constructor( public router: Router) {
}

Router Navigation

Using Links

Navigation can be incorporated using anchor tags in the template of the component for links navigable to the corresponding components as shown below:

template: `
<a routerLink="/login">Login</a>
<router-outlet></router-outlet>
`

In response to specific action

Navigation from one component to another on specific conditions can be handled by explicitly stating the result component with reference to the Router instance.

this.router.navigate(['/allstories']);

Conclusion

This blog simplifies the basic implementation of Angular Routing and introduces the concepts related to Angular Routing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s