Sunday, February 5, 2017

Basic routing in Angular 2.0 using Angular CLI

Angular 2 is one of the most popular JavaScript framework available today for creating web applications. It is a complete rewrite of AngularJS using Microsoft's TypeScript language (a strict superset of JavaScript).

To briefly understand Routing, consider it as the process of taking part of the URL endpoint and processing it into action.

Angular CLI is a command line interface for Angular. Both the CLI and generated project have dependencies that require Node 4 or higher, together with NPM 3 or higher.

To begin with we need to have Angular CLI installed on the workstation to start coding. To install CLI, we use command "npm install -g angular-cli". To update angular-cli to a new version, we can use below commands:

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

To verify if angular-cli is properly installed on your computer, we can run command "ng --version". It runs and shows version of angular-cli along with node.js version as shown in image below:

Basic routing in Angular 2.0 using Angular CLI

If version of angular-cli is visible, we can proceed to creating our demo project. To create a new project we execute command "ng new *project-name*". We can also create a project by default routing module. We can use command "ng new *project-name* --routing". Please refer below screen-shot for more information on success of project creation.

Basic routing in Angular 2.0 using Angular CLI




After successful completion, we try to run and see the blank project created by angular-cli. By default any new angular-cli blank project renders app.component. App component is the default root component for project. To run the Angular2 cli project we use command "ng serve". This command executes the project to run on port 4200 by default. We can access the compiled project at the browser by navigation to http://localhost:4200.

Basic routing in Angular 2.0 using Angular CLI


Basic routing in Angular 2.0 using Angular CLI

Once we have the project files ready, we will try creating three demo route pages. Let us assume the demo route pages to be home, aboutus and contactus. Using angular-cli commands we will create these three pages.

We will first add three web-links in the app.componet.html which will be used for navigation/routing.


<h1>
  {{title}}
</h1>
<ul>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#about">About Us</a></li>
  <li><a href="#contact">Contact Us</a></li>  
</ul>
<router-outlet></router-outlet>

Every component file once generated from angular-cli accompanies respective CSS file by default. We will add some CSS to format navigation bar.

app.component.css


ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover:not(.active) {
    background-color: #111;
}

.active {
    background-color: #4CAF50;
}

Finally we will rename the default title of the app to be "Routing Demo" by modifying the app.component.ts file


import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Routing Demo!';
}

Below is the output with the navigation bar.




As shown in above screen shot, we will add three components or pages using angular-cli to routing-demo project. The command for adding a component in angular-cli is "ng g component *my-new-component*" or "ng g c *my-new-component*"

Basic routing in Angular 2.0 using Angular CLI

Once we have all the three pages/components ready, we add these routes in routing module file which is "app-routing.module.ts"


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomepageComponent} from './homepage/homepage.component'
import {ContactusComponent} from './contactus/contactus.component'
import {AboutusComponent} from './aboutus/aboutus.component'

const routes: Routes = [      
   { path: '', component: HomepageComponent },
   { path: 'aboutus', component: AboutusComponent },
   { path: 'contactus', component: ContactusComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

The blank path ' ' is the root path. When the app loads, by default we want to load homepage or HomepageComponent. We will modify our template file, which is app.component.html file, so that the loaded pages show active links. It is a normal navigation requirement, in which any page we are visiting shows the active selected link.

app.component.html


<h1>
  {{title}}
</h1>
<ul>
  <li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}"><a routerLink="">Home</a></li>
  <li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}"><a routerLink="/aboutus">About Us</a></li>
  <li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}"><a routerLink="/contactus">Contact Us</a></li>  
</ul>
<router-outlet></router-outlet>

'routerLinkActive' is one of the attributes when using routing, the value assigned to it is the 'active' CSS class. We can define any CSS class and assign it to 'routerLinkActive'. The other attribute is 'routerLinkActiveOptions', by default the value is {exact:false}. We are using it with assigned value to be {exact:true}. It helps in tracking the active link or navigated link. Once the link is active then respective CSS class gets added to DOM.

Basic routing in Angular 2.0 using Angular CLI


The complete working example can be seen in video below:




Download completed project file - Click here

-Nitin


No comments:

Using FormBuilder, Validators & FormGroup in Angular 2 to post data to Node server (node.js)

This blog explains usage of  FormBuilder , Validators , FormGroup classes in Angular 2 projects. In this post we will create HTML form a...