Routing and Navigation in detail :Angular2


So, are you wondering how to start routing in Angular2? I am so glad you are here. This blog is going to be all about routing and navigation in Angular2. Routing and navigation is the core concept of Angular2 . Alright let’s dive into routing and navigation and take a close look at it.

Now, We will be discussing following points in this article.
1. Why routing is necessary
2. Define routes for pages
3. Link to Routes
4. Navigate from Code
5. Route Guards
6. Route Based Link Styling
7. Lazy Loading
8. Code Clean Up

Let’s discuss the above points one by one.

Why routing is necessary
Routing helps in directing users to different pages based on the option they choose on the main page. Hence, based on the option they choose, the required Angular Component will be rendered to the user.

Define routes for pages

Now, before you define routes for pages. Let’s see

Most routing applications should add a element to the index.html as the first child in the tag to tell the router how to compose navigation URLs.

Step 1 − Add the base reference tag in the index.html file.
Before we define define routes for the pages, Let’s create files for the pages.

For example
Let’s create Inventory.component.ts and Product.component.ts and write simple logic like below

import {Component} from '@angular/core';
@Component ({ selector: 'app-root',template: '
<h1>Inventory</h1>
'})
export class InventoryComponent {}

When we are done writing the components for the application then we should mention the component in app.module.ts under declaration and then finally define routes in the route.ts file like below.

{ path: 'products', component: ProductComponent}, // product route
{ path: 'product/:id', canActivate: [ProductGuardService], component: ProductDetailComponent}, // product route
{ path: 'inventory', component: InventoryComponent}, // inventory route

Now in app.component.html file add the following code.

<ul>
<li>
  <a [routerLink]="['/inventory']">Inventory</a>
</li>
<li>
  <a [routerLink]="['/product']">Products</a>
</li>
</ul>

Run your application and try to hit link and you will be redirected to a page with the corresponding component loaded.

Link to Routes

The RouterLink directives on the anchor tags give the router control over those elements. The navigation paths are fixed, so you can assign a string to the routerLink (a “one-time” binding).

That is how you navigate from one page to another

	&amp;lt;li&amp;gt;&amp;lt;a routerLink="/home"&amp;gt;Home&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;

Adding an error route
We can also add an error route. In Routing, one can also add an error route. This can happen if the user goes to a page which does not exist in the application.

Step1. Add a PageNotFound component as NotFound.component.ts.

Step2. Add the below line in route.ts file

{path: ‘**’, component: PageNotFoundComponent}
** is for any route which does not fit the default route. They will be directed to the PageNotFoundComponent component.

Navigate from code
Of course, You can navigate from page to another using code. Let’s see How do we do that.

We will need to inject router in the constructor and call navigate function.

export class TestComponent {constructor(private router: Router) {}
back() {
this.router.navigate([‘/’]);}}

Router Guards
Sometimes we want to prevent a user from going to a particular page or discourage them from leaving a page. That’s what route guards are designed for.

Route guards have two properties
1. Can Activate
2.Can Deactivate

We can use ‘Can activate’ to prevent a user from going to a page which does not exist yet for the application. This is often helpful when a user is trying to access the page which should create an error.

We can use ‘Can deactivate’ to prevent a user from leaving a page. This is often helpful when a user is leaving the page before saving the data.

Router based linking style
If you have a header in your website and you want to highlight the currently active link then you can do that by using “routerLinkActive”

Step1 Add the html in your webpage like below

&amp;lt;ul id="nav-bar"&amp;gt;
	&amp;lt;li&amp;gt;&amp;lt;a routerLink="/home" routerLinkActive="active"&amp;gt;Home&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
	&amp;lt;li&amp;gt;&amp;lt;a routerLink="/about" routerLinkActive="active"&amp;gt;About Us&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
	&amp;lt;li&amp;gt;&amp;lt;a routerLink="/service" routerLinkActive="active"&amp;gt;Services&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
	&amp;lt;li&amp;gt;&amp;lt;a routerLink="/contact" routerLinkActive="active"&amp;gt;Contact Us&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;

Step2. Add css
#nav-bar li > a.active {
color: black;
}

Lazy loading

Let’s dive into this cool feature of Angular2 Router i.e Lazy Loading of modules.
So we have this small app which has basically 3 modules:
AppModule – This is the root module of the application
TasksModule – This is the child module of AppModule
UsersModule – Child module of AppModule, sibling module of TasksModule

Before we move on further, let’s note that there are 3 other important parts of this app:
ROUTING – This is the main router for our application.
TASKS_ROUTING – This is the child router. Takes care of routing for tasks module.
USERS_ROUTING – Takes care of routing for users module.

Lazy loading is also used to optimize app loading time because only the modules which are needed at run time will be loaded. With lazy loading we can split our application to feature modules and load them on-demand. The main benefit is that initially we can only load what the user expects to see at the start screen. The rest of the modules are only loaded when the user navigates to their routes.

Lazy loading is one of the best features of the router.

So far our app has only one module and that is app module. Let’s see how we can add multiple module.
Our application can be broken down into smaller sections. We will add in a user module.
Lazy loading is the ability to load the pieces on demand. Lazy loading modules helps us decrease the startup time. In lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes.

For example
If we want to add in a new module, we will first create a new folder under app directory. If user is the new module we want to add in our application we will first create a user directory under app directory and add in all the related files like component, html, css and route files. Then we also need to add in one more line into main route file which is under app directory

Line to be added in route.ts file

{path: 'user', loadChildren: 'app/user/user.module#UserModule'},

That’s how we are adding in a new module which is a UserModule. Now this module will only be loaded when a user tries to access the said routes.

Code Clean up

In order to clean up the code, we can expose all of the imports inside the directory from a single index file and then we can just import it with a single import line. This is referred to as creating barrells.

Step 1. Create an index file. Add below mentioned line i.e you can mention as many component as you want.
export * from ‘./test.component’

Step 2. In app module

import {
} from ‘./index’

you can simply mention all the components inside the above block. This will make your app.module file cleaner. We can also say this falls under best practices.

If you find any challenge, Do let me know in the comments.If you enjoyed this post, I’d be very grateful if you’d help it spread.Keep smiling, Keep coding!

 knoldus-advt-sticker

Advertisements

About deepak028

There is nothing much to describe me.However, I am a very ordinary person who believes in sharing knowledge.
This entry was posted in Scala. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s