Angular2 Routing step by step
Introduction
This article is about the routing in Angular2. The Angular Router enables navigation from one view to the next as users perform application tasks. The Component Router is a highly configurable and feature packed router. Features included are standard view routing, nested child routes, named routes, and route parameters.
Background
To achieve routing in the Angular2 there are mainly three components are there, those are mentioned below.
- Routes
- RouterOutlet
- RouterLink
Routes
Route is an object that we use on our application component that describes the routes we want to use. For instance, we could write our routes like this:
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent}
];
Routes are array of key value pair. It consists of two attributes path and component. Path refers to the URL has to displayed in the browser and the component contains the logic to redirect the respective page.
The idea is that we might put our home page at the URL /home and our about page at /about. In Angular 2, we’d have a HomeComponent for the /home page and AboutComponent for the /about page. In the common case, a router lets us map these URLs to a component.
RouterOutlet
The RouterOutlet directive tells our router where to render the content in the view.
For instance, if we have a view:
@Component({
selector: 'demo-app',
template: `
<a [routerLink]="['/']">Home</a>
<a [routerLink]="['/about']">About</a>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent { }
In the above Component we have <router-outlet> inside a div. This directive refers to load the view during runtime with the view content.
RouterLink
If we want to navigate between routes, we use the RouterLink directive. So if we wanted to link to our home and about page from a navigation, we could change our view above to something like this:
<a [routerLink]="['/']">Home</a>
<a [routerLink]="['/about']">About</a>
In the above code snippet, routerLink is defined. In the above example home is the default page, / will also redirect on the home page and on click on Home it will redirect to the /about page.
Project Creation Step by Step:
The index.html is the entry point to your application:
- it links all the required poly fills in the header,
- it configures module loading for your app using System.js,
- it establishes the main module of your application as app
- it provides the HTML mark up for your application with the custom <demo-app> element.
<!DOCTYPE html>
<html>
<head>
<title>Angular 2</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="https://unpkg.com/core-js/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.6.21?main=browser"></script>
<script src="https://unpkg.com/reflect-metadata@0.1.3"></script>
<script src="https://unpkg.com/systemjs@0.19.27/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<demo-app>Loading...</demo-app>
</body>
</html>
Bootstrapping the Application:
In Angular 2 we use a bootstrapper. The SystemJS configuration contained in systemjs.config.js and the System.import('app') tell SystemJS to import the entry module to your application 'app'.
If you take a look at the systemjs.config.js file you’ll discover the following lines that tell system.js that the main module to load resides in the app/main.js file (app/main.ts before transpilation):
app: 'app',
'main': 'main.js',
---------------------------------------------
packages: {
'app/core': { main: 'index' }, // PAPA
'app/models': { main: 'index' }, // PAPA
'api': { defaultExtension: 'js' }, //PAPA
app: {
main: './main.ts',
defaultExtension: 'ts'
},
rxjs: {
defaultExtension: 'js'
}
}
The app/main module contains the bootstrapping code for your Angular 2 application and it looks like this:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);
It imports the platformBrowserDynamic from the @angular/platform-browser-dynamic and AppModule from the app.module residing in the app folder and passing it as argument for bootstrapModule function.
The imported AppModule looks like below.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
import { AboutComponent } from './about.component';
import { HomeComponent } from './home.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes)
],
declarations: [
AboutComponent,
HomeComponent,
AppComponent
],
providers: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
In the above code, two things we need to notice that we are importing the AppComponent and passing it as bootstrap component and importing routes from the app.routes. Below is the code of routing which is imported from the app.routes.
import { Routes } from '@angular/router';
import { AboutComponent } from 'app/about.component';
import { HomeComponent } from 'app/home.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent}
];
In the above code we have imported the HomeComponent and AboutComponent for routing. For routing we have created object routes of Routes type and path and component we are passing as parameter to enable routing.
In the AppModule we have mainly imported routes and AppComponent. Above we have shown displayed the route code and below is the AppComponent code is written.
import { Component } from '@angular/core';
@Component({
selector: 'demo-app',
template: `
<a [routerLink]="['/']">Home</a>
<a [routerLink]="['/about']">About</a>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent { }
In the above AppComponent code one thing to notice that we have demo-app as selector. This directive is written in the index.html page it means that template content will render in the demo-app directive of the index.html page.
In the template section Home and About is there as anchor link for routing defined as routeLink and route-outlet directive is the placeholder of the rendered view.
As we have implemented the routing logic in above codes for home and about page. So to implement the routing logic we will create new HomeComponent and AboutComponent.
Content of the HomeComponent:
import { Component } from '@angular/core';
@Component({
// selector: '',
template: `<h2>Home</h2> `
})
export class HomeComponent { }
Content of the AboutComponent:
import { Component } from '@angular/core';
import { ActivatedRoute, ROUTER_DIRECTIVES } from '@angular/router';
@Component({
// selector: '',
template: `<h2>About page</h2> `
})
export class AboutComponent { }
In both the above component, template is defined, that will be rendered in the browser.
NOTE: Complete code is posted on GitHub ( https://github.com/Rajan-Kumar/Angular2 ).