Thursday, November 1, 2018

Eager loading Module example in Angular 6

Eager loading is the default type of module loading in Angular, this approach is suitable for smaller applications where all the dependent modules are loaded initially when the application is loaded in the browser.

In eager loading we import all the dependent components into the main module and map the components to different routes in the module routing. When a specific route is invoked the corresponding component is loaded in the root component.

This example is similar to the one which we saw in the Routing example. We import 2 components About & Contact in the application module and map them in the modules routing configuration.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RouteAppComponent } from './route-app/route-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 },
  { path: 'contact', component: ContactComponent }
];

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

When a specific route is invoked the corresponding component is loaded in the root component in place of the route-outlet placeholder. The route component’s template will look like this.

<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">
      This is the Home page of the Routing Component
      <router-outlet></router-outlet>
    </td>
  </tr>
</table>


The output will be as follows



Search Flipkart Products:
Flipkart.com

No comments: