Friday, 22 September 2017

Routing - Angular

What are the main routing Component?
Angular provides 3 different components for routing configuration:

Routes is the configuration to describe application’s different routes
RouterOutlet is a “placeholder” component that holds the view for each route
RouterLink is a directive to link to routes

Routes:
Routes is an object to describe the routes of the application.

const routesRoutes  = [
    { path: ''redirectTo: 'login'pathMatch:'full' },
    { path: 'login'component: LoginComponent },
    { path: 'home'component: HomeComponent ,
     children: [
      { path: ''component: DashBoardComponent },
      {path: 'events'component: EventsComponent}
     ]},
    { path: 'register'component: RegisterComponent },
    { path: 'about'component: AboutComponent },
    { path: '**'component: p404Component },
   ];

We have configure routes which is an array of Route. Each entry of the array is The complete list of possible fields used in this configuration are as following:
  • path – url of the route used by the matcher DSL.
  • component –name of the target component.
  • pathMatch – specifies the matching strategy, example : full.
  • redirectTo -url that will replace the current matched segment in case of redirection.
  • outlet – name of the outlet used as a placeholder for the component. If there is no outlet it would be placed in <router-outlet>
  • canActivate – array of DI tokens used to find CanActivate handlers.
  • canActivateChild – array of DI tokens used to find CanActivateChild handlers.
  • canDeactivate – array of DI tokens used to find CanDeactivate handlers.
  • children-  is an array used to define nested routes.
Router Directives
Angular RouterModule has 3 different directives. Such as:
  1. router-outlet
  2. router-link
  3. routerLinkActive
router-outlet:
router-outlet is a component from angular/router library. The router is the placeholder to display views inside  <router-outlet> tags. As the routes changes, the view inside the <router-outlet> tags also change accordingly.

<div class="container">
<router-outlet></router-outlet>
</div>

router-link:
router-link directive is an alternative of HTML href property. The syntax is as following:
<div class="navbar navbar-default">
<a class="navbar-brand" [routerLink]="['/']">Angular App</a>
<ul class="nav navbar-nav">
<li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/']">Data Binding</a>
</li>
<li routerLinkActive="active">
<a [routerLink]="['/about','2']">About Us</a>
</li>
<li routerLinkActive="active">
<a [routerLink]="['/inheritance']">Inheritance</a>
</li>
</ul>
</div>
If we want to pass the queryParams in an object , we can also do that as following:
<a [routerLink]="['/about', {id:'2'}]">About Us</a>
Or
<a [routerLink]="['/about','2']">About Us</a>
routerLinkActive:
The RouterLinkActive directive toggles css classes for active RouterLinks based on the current RouterState. This cascades down through each level in our route tree, so parent and child router links can be active at the same time. To override this behavior, we can bind to the [routerLinkActiveOptions] input binding with the { exact: true } expression. By using { exact: true }, a given RouterLink will only be active if its URL is an exact match to the current URL.
<li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/']">Data Binding</a>
</li>

How to  handle Routing in Angular2?

There are following steps to complete achieve this Goal, such as

  • Create App Router Module
     a. Configuration different Paths
  • Import RouterModule to AppModule
  • Create Router-Outlet view and associated component
  • setup router-link directive
Defining Routes
Let’s create a file called app.routes.ts in the root of the app folder. This file will describe the configuration for routers for the application. 
import { NgModule } from '@angular/core';
import { RoutesRouterModule } from '@angular/router';
import { DatabindingComponent } from './databinding/databinding.component';
import { AboutComponent } from './about/about.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { ChildComponent } from './inheritance/child.component';

const routesRoutes = [
path: ''component: DatabindingComponent },
path: 'about/:id'component: AboutComponent },
path: 'inheritance'component: ChildComponent },
path: '**'redirectTo: 'notfound'pathMatch:'full' }
];

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

Then the last route we will add is a wildcard route. This will match any routes that we have defined. This is also why we added the redirect. If we didn’t, our app would start at this route since we start from a route that is not defined, an empty route.

After adding the redirect, any route that we type that doesn’t exist will get our error page.

Here the routes has been passed as the argument to RouterModule.forRoot() so that the RouterModule in our imports is able to use the RouterOutlet and RouterLink components in this module. Create Router-Outlet view and associated component

For this example, we have placed a placeholder on app.component.html as following:

<div class="container">
<router-outlet></router-outlet>
</div>

The Main AppComponent

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

Setup router-link directive

Now we have to write the router-link to place the actual link on html. Therefore, we change the app.component.html and add the router link as following:

<div class="navbar navbar-default">
<a class="navbar-brand" [routerLink]="['/']">Angular App</a>
<ul class="nav navbar-nav">
<li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/']">Data Binding</a>
</li>
<li routerLinkActive="active">
<a [routerLink]="['/about','2']">About Us</a>
</li>
<li routerLinkActive="active">
<a [routerLink]="['/inheritance']">Inheritance</a>
</li>
</ul>
</div>
<div class="container">
<router-outlet></router-outlet>
</div>

RouterModule.forRoot versus RouterModule.forChild
There are two methods we can invoke using RouterModule in order to register routes.

In case we declare the top-level routes of our application, we need to use RouterModule.forRoot. This method will register the top-level routes and return the routing module that should be imported by the root module of the application.

If we want to define routes in a lazy-loaded module and import the module returned by the invocation of the forRoot method, we'll get a runtime error. This is because the forRoot method will return a module with providers, which should be imported only once, by the top-level module. In order to register nested routes in a lazy-loaded module, we will need to use the forChild ...

Some Points to know: 
  • The routerLink directive tells the router where to navigate when the user clicks the link.
  • The routerLinkActive directive is used to add the active bootstrap class to the HTML navigation element whose route matches the active route.
  • The router-outlet directive is used to specify the location where we want the routed component's view template to be displayed.
  • The routerLink, routerLinkActive and router-outlet directives are provided by the RouterModule which we have imported in our application root module.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives