Tuesday, March 24, 2020

Angular Routing


Routing in is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. Angular routes enable the user to create different URLs for different content in an application. Routing in angular is an essential part of the angular framework contained in the @angular/router package. It,
·     Helps developers build single-page applications with multiple states and views using routes and components
·       Allows client-side navigation and routing between various components
·       Allows lazy loading of modules
·   Add router guards for client-side protection and allow or disallow access to the components or modules
·    Various path matching strategies (i.e. prefix and full) to tell the router how to match a specific path to a component
·       Easy access to route and query parameters

Routes and Paths in Angular Routing

In angular, a route is an object that provides information about which component maps to a specific path. A path is a fragment of a url that determines where exactly the resource is located the user wants to access. In angular, developers can define a route using route configurations or instance of the Router interface. Each route has the following properties i.e.
·       path: Specifies the path of the route
·       pathMatch: Specifies the matching strategy (i.e. prefix or full)
·       component: Specifies the component that is mapped to a route
·       redirectTo: Url which users will be redirected to if a route is a matched

For instance,

path: 'list'component: StudentListComponent }

Navigation Directives in Angular Routing

Angular Router provides the routerLink directive to create links. This replaces the href attribute in the anchor tag. It also provides the routerLinkActive for marking a link as active. For instance,

<a routerLink="list">List-Students</a> 
Always remember, an angular router can support more than one outlet in the same application. The main outlet is called as a primary outlet and other outlets are called secondary outlets. Now open the visual studio code and let us see how to implement this tutorial in angular 6 frameworks.

Router Outlet

The router-outlet tag in angular is a directive exported by the RouterModule and acts as a placeholder to the router where it needs to insert the matched components. It is represented by the following syntax.

<router-outlet></router-outlet>

Angular Router and Navigation Example

Step-1: In order to perform routing into our application, we need to add code in our app.component.ts file, because navigation bar will be available at our main application. To perform routing add following module: 

import { RouterModuleRoutes } from '@angular/router';

·   Router Module: Router module contains the Router service and Router directives such as (RouterLink, RouterLinkActive, RouterOutlet etc).
·     Routes: To configure routes, we also need to import Routes type from '@angular/router'. If you look at the definition of Routes type, it is actually an array of Route objects. This Routes type is not required for the application to work. However, using it provides us intellisense and compile time checking. For example, mis-spelled properties of the Route object will be reported as errors.
·    We should also add RouterModule.forRoot(appRoutes) method that creates a routing module that includes the router directives, the route configuration and the router service.

app.component.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterModuleRoutes } from '@angular/router';

const appRoutesRoutes = [
  path: 'list'component: StudentListComponent },
  { path: 'create'component: CreateStudentComponent },
  { path: 'like'component: LikeComponent },
  { path: 'cricket'component: CricketerComponent },
  { path: ''redirectTo: '/list'pathMatch: 'full' },
  { path: 'link-1'component: TemplateFormComponent },
  { path: 'link-2'component: ReactiveFormComponent }
];

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CricketerComponent } from './cricketer/cricketer.component';
import { LikeComponent } from './like/like.component';
import { StudentListComponent } from './student/student-list.component';
import { TemplateFormComponent } from './template-form/template-form.component';
import { ReactiveFormComponent } from './reactive-form/reactive-form.component';
import { CreateStudentComponent } from './student/create-student.component';

@NgModule({
  declarations: [
    AppComponent,
    CricketerComponent,
    LikeComponent,
    StudentListComponent,
    TemplateFormComponent,
    ReactiveFormComponent,
    CreateStudentComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}


Step-2: To Create the application menu and tie the routes to it. Notice we are using routerLink directive. This directive tells the router where to navigate when the user clicks the link. We are also using router-outlet directive. This directive specifies where you want the routed component view template to be displayed. We want our navigation menu to be always displayed, so the ideal location for it is the root component AppComponent i.e app.component.html file. When the application first loads, it loads the root AppComponent in index.html. So let's place the following HTML in app.component.html file.

app.component.html
<div class="container">
  <nav class="navbar navbar-default">
    <ul class="nav navbar-nav">
      <li>
        <a routerLink="list">List-Students</a>
      </li>
      <li>
        <a routerLink="create">Create Student</a>
      </li>
      <li>
        <a routerLink="like">Like Component</a>
      </li>
      <li>
        <a routerLink="cricket">Cricket Component</a>
      </li>
      <li>
        <a routerLink="link-1">Template Form</a>
      </li>
      <li>
        <a routerLink="link-2">Reactive Form</a>
      </li>
      <li>
        <a routerLink="service">Services</a>
      </li>
    </ul>
  </nav>

  <router-outlet></router-outlet>
</div>

As you can see, in the HTML we have 2 things - Navigation menu and the <router-outlet> directive. The navigation menu is always displayed. Below the navigation menu, we have the <router-outlet> directive. This is the location where the routed component view template is displayed. 

For example, when we click on the 
"List" link in the navigation menu, the route changes to "/list" and the Student-List Component view template is displayed at the location where we have the <router-outlet> directive. At this point, if we click on "Create" link, 2 things happen

1.     The route changes from "/list" to "/create" 
2.     Student-ListComponent view template is replaced with Create-StudentEmployeeComponent view template
3.     Also notice, if we navigate to the root of the application i.e if we do not include "/list" or "/create" in the URL, the router automatically redirects us to "/list". This is because of the following empty route we have in our route configuration.

{ path: 
'', redirectTo: '/list', pathMatch: 'full' }

We are using 
Bootstrap-3 navbar component to create the navigation menu.

Code Output: