Sunday, November 4, 2018

Angular Routing

Routing in Angular is used to load different components based on the route selected by the user. Routing is essential for medium to larger size applications since we cannot load all the components in a single view.

If you have worked on MVC applications you know that there is a route handler which parses the request route and redirect to the corresponding view. Angular Routing is similar the Routing module handles the request route and loads the corresponding component.

The routing services in Angular are present in the package @angular/router
, we need to import RouterModule, Routes from this package to implement routing in Angular.

To define routes and mapping components, we need to create a appRoutes array with routes and components and import the routes into the module using RouterModule.forRoot(appRoutes)

const appRoutes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent }
];

imports: [ RouterModule.forRoot(routes) ]

Once we add the routes to the module, we need to add placeholder where the route templates will be loaded, this is done by adding a tag in the root component. When a route is invoked the corresponding component will be loaded in place of the router-outlet tag.

<td class="content">
            router-outlet></router-outlet>
</td>

Now we defied where the component should be loaded, next we shall define the UI definitions for the route. i.e the UI elements which the user should activate to enable the routes, they can be defined in links, buttons, etc or any UI components using the routerLink attribute as follows.

<a routerLink="/about">About</a>
<a routerLink="/contact">Contact</a>

Below is the full example to implement the Routing in Angular

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './route-app/about/about.component';
import { ContactComponent } from './route-app/contact/contact.component';

const appRoutes: Routes = [
  { path: 'about', component: AboutComponent, canActivate: [RouteGuard] },
  { path: 'contact', component: ContactComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    AboutComponent,
    ContactComponent
  ],
  imports: [
    RouterModule.forRoot(appRoutes),
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


app.component.html

<table class="layoutTable">
  <tr>
    <td class="leftMenu">
        <a routerLink="/about" routerLinkActive="active">About</a><br/>
        <a routerLink="/contact" routerLinkActive="active">Contact</a><br/>
    </td>
    <td class="content">
      <router-outlet></router-outlet>
    </td>
  </tr>
</table>

Output:


Search Flipkart Products:
Flipkart.com

No comments: