This article is in continuation of our previous article on Routing in Angular 2. If you haven’t had a look at it, please refer this link. In our last part, we saw how we can define routes for the application; also, we saw how to define Child routes for the featured modules of the application.
In this part, we’ll look what Auxiliary routes are and how we can achieve lazy loading through routing. So, first thing first, what Auxiliary routes are.
Auxiliary Routes
They are same as the normal route except with named router outlet i.e. while defining auxiliary route definition, you’ll be providing the router outlet name so as to specify where the contents should be displayed. Also, the router-outlet defined in your HTML code will have the name property defined. This is the most common scenario where we need to display master-details records on the same page next to each-other.
Syntax
- {path:yourURL Path, component: yourComponent, outlet: “routerOutletName”}
In your HTML.
- <router-outlet name= “routerOutletName”></router-outlet>
NOTE
The name defined for router-outlet element in your HTML should be same as defined in your route configuration outlet property value.
For demonstrating what Auxiliary routes are, we’ll create a new component with the name “EmployeeInfoComponent” where we’ll display the list of all employee Ids as hyperlink and on click of any employee ID, that particular employee record details should be displayed on the right hand side of the page, using EmployeeDetailsComponent which we’ve created in our 1st part. The below picture describes the same.
To achieve this, we need to do the below steps.
- Add new methods to “EmployeeService” as per our business requirement i.e. a function returning the list of all “EmpIds” and a function returning employee details based on “EmpId”. Here is the updated code snippet for the same.
- import { Injectable } from '@angular/core';
- import { Http, Response } from '@angular/http';
- import { IEmployee } from './employee';
- import { Observable } from 'rxjs/Observable';
-
- @Injectable()
- export class EmpService {
-
- private _repositoryURL: string = "app/emp/emp-data.json";
-
- constructor(private http: Http) {
- }
-
-
-
-
- public getEmployees(): Observable<IEmployee[]> {
- return this.http.get(this._repositoryURL)
- .map((response: Response) => { return <IEmployee[]>response.json() })
- .catch(this.handleError);
- }
-
-
-
-
- public getEmployeeIDs(): Observable<string[]> {
- return this.http.get(this._repositoryURL)
- .map((response: Response) => {
- return <string[]>(<IEmployee[]>response.json()).map(function (jsonObj: IEmployee) {
- return jsonObj.empId
- });
- })
- .catch(this.handleError);
- }
-
-
-
-
- public getEmployee(eid: string): Observable<IEmployee> {
- return this.http.get(this._repositoryURL)
- .map((response: Response) => {
- return <IEmployee>(<IEmployee[]>response.json()).filter(function (objEmp: IEmployee, idx: number) {
- return objEmp.empId === eid;
- })[0];
- })
- .do(eData => console.log(eData))
- .catch(this.handleError);
- }
-
- private handleError(errorResponse: Response) {
- console.log(errorResponse.statusText);
- return Observable.throw(errorResponse.json().error || "Server error");
- }
- }
- Create a new named router-outlet in your application root component HTML fragment. Below is the updated code snippet for “app.component.ts” file.
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'my-app',
- template: `<nav class="navbar navbar-inverse">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
- <span class="sr-only">Toggle navigation</span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- <a class="navbar-brand" href="#">{{orgName}}</a>
- </div>
- <div class="collapse navbar-collapse" id="navbar">
- <ul class="nav navbar-nav">
- <li><a routerLink="welcome" routerLinkActive="active">Home <span class="sr-only">(current)</span></a></li>
- <li><a routerLink="emp-list" routerLinkActive="active">Emp-List</a></li>
- <li><a routerLink="emp-info" routerLinkActive="active">E-Details</a></li>
- </ul>
- </div>
- </div>
- </nav>
- <div class='container'>
- <div class="col-md-7">
- <router-outlet></router-outlet>
- </div>
- <div class="col-md-5">
- <router-outlet name="detailsOutlet"></router-outlet>
- </div>
- </div>`
- })
- export class AppComponent {
- orgName: string = "Angular2 Series";
- }
NOTE
- We’ve defined a named router-outlet “detailsOutlet”. Now, there are 2 router- outlets in our HTML code. By default, the one without name will be used by Angular for displaying child/navigated pages. When we specify that the data of a particular component to be displayed in the “detailsOutlet”, then only the details will be displayed in the “detailsOutlet” section.
- We’ve added a new menu-item named “emp-info” which will help us navigate to the newly created component “EmployeeInfoComponent”.
- Create EmployeeInfoComponent: A simple component which lists all employee Ids as hyperlink. Below is the code snippet for the same.
- import { Component, OnInit } from '@angular/core';
- import { EmpService } from './emp.service';
-
- @Component({
- selector: 'emp-info',
- templateUrl: './app/emp/emp-info.component.html'
- })
- export class EmployeeInfoComponent implements OnInit {
- pageTitle: string = "Employee Info";
- imageWidth: number = 125;
- imageHeight: number = 125;
- errorMessage: string;
- eIds: string[];
-
- constructor(private empService: EmpService) {
- this.eIds = [];
- }
- ngOnInit(): void {
- let self = this;
- self.empService.getEmployeeIDs().subscribe(empData => this.eIds = empData,
- error => this.errorMessage = <any>error);
- }
- }
NOTE
In ngOnInit method, we are loading all the employee Ids by calling the employee service method and storing all those in eId’s [].
- component.html
- <ul class="list-group" style="width: 450px;">
- <li class="list-group-item" *ngFor="let id of eIds">
- <a [routerLink]="['/emp-info',{outlets: {'detailsOutlet': ['emp-details',id]}}]">{{id}}</a>
- </li>
- </ul>
NOTE
- Look at the special syntax for defining routerLink with outlet property value.
- routerLink is defined as an array, since we are passing multiple parameters to it. That’s why it is enclosed in [] box brackets.
- “/emp-info” refers to the parent URL path.
- “outlets”: Angular2 property for defining outlet name.
- “detailsOutlet” is the name of our router-outlet element defined in our root Component HTML.
- “emp-details” refers to the child URL path where we need to navigate by passing employee Id as the parameter which is the last segment.
- We also need to update our EmployeeDetailsComponent where we need to load the employee details based on “employeeId” passed as query string parameter. In our first part on routing, we just left this component with text “Employee Details Component”; now, it’s time for us to write code for fetching employee details based on “employeeId”. Here is the updated code snippet for the same.
- import { Component, OnInit } from '@angular/core';
- import { ActivatedRoute, Router, Params } from '@angular/router';
- import { EmpService } from './emp.service';
- import { IEmployee } from './employee';
-
- @Component({
- selector: "emp-details",
- templateUrl: "./app/emp/emp-details.component.html"
- })
- export class EmployeeDetailsComponent implements OnInit {
- pageTitle: string = "Employee Details";
- imageWidth: number = 125;
- imageHeight: number = 125;
- empId: string;
- empData: IEmployee;
- errorMessage: string;
-
- constructor(private route: ActivatedRoute, private router: Router, private empService: EmpService) {
- this.empId = "";
- this.empData = null;
- }
-
- ngOnInit(): void {
- this.route.params.subscribe(params => {
-
- this.empId = params["eid"];
-
- this.empService.getEmployee(this.empId).subscribe(empData => this.empData = empData, error => this.errorMessage = <any>error);
- });
- }
- }
- Below is the updated HTML fragment for employee-details.component.html.
- <div class="col-md-12 text-center">
- <div class="panel panel-primary">
- <div class="panel-heading">
- <h4>Employee Details: {{empId}}</h4>
- </div>
- <div class="panel-body" *ngIf="empData!=null">
- <div class="row">
- <div class="col-md-4">
- <img [src]="empData.photo" [style.width.px]='imageWidth' [style.height.px]='imageHeight' />
- </div>
- <div class="col-md-8">
- <table class="table table-striped table-bordered">
- <tbody>
- <tr>
- <td>Name: </td>
- <td class="leftAlign">{{empData.name|uppercase}}</td>
- </tr>
- <tr>
- <td>Email:</td>
- <td class="leftAlign">{{empData.email|lowercase}}</td>
- </tr>
- <tr>
- <td>Phone:</td>
- <td class="leftAlign">{{empData.phone}}</td>
- </tr>
- <tr>
- <td>Salary:</td>
- <td class="leftAlign" [formatSalary]='empData.salary' defaultTextColor="#0e0e6c">{{empData.salary|currency:'INR':true:'1.2-2'}}</td>
- </tr>
- <tr>
- <td>Appraisal Rating:</td>
- <td>
- <ar-star [appraisalRating]="empData.appraisalRating"></ar-star>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- </div>
- </div>
- Define routing configuration for Auxiliary routes. Here is the updated emp-route.config.ts file.
- import { Routes } from '@angular/router';
-
- import { EmployeeListComponent } from './emp-list.component'
- import { EmployeeDetailsComponent } from './emp-details.component';
- import { EmployeeInfoComponent } from './emp-info.component';
-
- export const eRoutes: Routes = [
- {
- path: 'emp-list',
- children: [
- { path: '', component: EmployeeListComponent },
- { path: 'emp-details/:eid', component: EmployeeDetailsComponent }
- ]
- },
- {
- path: 'emp-info',
- children: [
- { path: '', component: EmployeeInfoComponent },
- { path: 'emp-details/:eid', component: EmployeeDetailsComponent, outlet: "detailsOutlet" }
- ]
- }
- ]
NOTE
- We’ve defined “emp-info” as the parent path which has 2 child routes defined.
- If the path is empty then load “EmployeeInfoComponent. The default route.
- If path is “emp-details/:eid, then load EmployeeDetailsComponent. In the same path, we also specified outlet: “detailsOutlet” i.e. the EmployeeDetailsComponent should be loaded in the detailsOutlet router-outlet HTML element. Remember, we’ve defined this outlet in our root component with name “detailsOutlet”. The same name is passed here.
- Registering & exporting our newly created component with/from emp-module. Here is the updated code snippet for the same.
emp-module.ts
- import { NgModule } from '@angular/core';
- import { FormsModule } from '@angular/forms';
- import { RouterModule } from '@angular/router';
- import { CommonModule } from '@angular/common';
- import { EmployeeListComponent } from './emp-list.component';
- import { EmployeeSearchPipe } from './emp-search.pipe';
- import { FormatSalaryDirective } from './emp-formatsalary.directive';
- import { EmpService } from './emp.service';
- import { SharedModule } from '../shared/shared.module';
- import { EmployeeDetailsComponent } from './emp-details.component';
- import { EmployeeInfoComponent } from './emp-info.component';
-
- @NgModule({
- imports: [CommonModule, FormsModule, SharedModule, RouterModule],
- declarations: [EmployeeListComponent, EmployeeSearchPipe, FormatSalaryDirective, EmployeeDetailsComponent, EmployeeInfoComponent],
- providers: [EmpService],
- exports: [EmployeeListComponent, EmployeeDetailsComponent, EmployeeInfoComponent]
- })
- export class EmpModule {}
That’s it. We are done. Try running the application and you’ll see the below output on click of any employeeID. Hereby, displaying the master-detail record.
This is what Auxiliary routes are. Now that you know, you can further explore it in your own way.
Lazy loading modules in Routing
Lazy loading, in simple terms, means load something on demand. We can implement lazy loading in Angular 2 by means of Routing and featured modules. In lazy loading, until and unless a particular module is requested, it won’t be loaded. The benefit of doing so is that it will reduce the startup/bootstrap time of the application. On the initial load, the application will load only the necessary files and rest of the modules/files will be loaded only when user tries to access them. For demonstrating this, we’ll convert our eager loading application to lazy loading.
For now, we’ve separate modules which are finally loaded in our root application module. This is called eager loading i.e. loading everything before-hand; even if the user doesn’t access our “emp-list” or “emp-info” component, it will still be loaded at the startup time.
I’m accessing home page of our application but in the network tab, you can see the application loads everything including the “employee-module” which is not been accessed by the user. Below snap describes the same.
To lazy load things, we need to make a couple of changes.
- Remove featured modules imported from our application root module from app.module.ts file. So from our root module file, we’ll remove “empModule” import. Here is the updated code snippet for the same.
-
- import { NgModule } from '@angular/core';
- import { FormsModule } from '@angular/forms';
- import { BrowserModule } from '@angular/platform-browser';
- import { HttpModule } from '@angular/http';
- import { RouterModule, Routes } from '@angular/router';
-
- import { AppComponent } from './app.component';
- import 'rxjs/Rx';
- import { routeConfig } from './app.route-config';
- import { WelcomeComponent } from './welcome/welcome.component';
-
- @NgModule({
- imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(routeConfig)],
- declarations: [AppComponent, WelcomeComponent],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
- Update our application root route config file i.e. app.route-config.ts to lazy load things using the loadChildren property.
- import { Routes } from '@angular/router';
-
- import { WelcomeComponent } from './welcome/welcome.component';
-
- export const routeConfig: Routes = [
- {
- path: 'welcome',
- component: WelcomeComponent
- },
- {
- path: 'empLazy',
- loadChildren: 'app/emp/emp.module#EmpModule'
- },
- {
-
- path: '',
- component: WelcomeComponent
- },
- {
-
- path: '**',
- component: WelcomeComponent
- }
- ]
NOTE
As you can see that I’ve created one path named “empLazy” and using the loadChildren property, I’m lazily loading the “EmpModule”.
- Update your routerLink to the new path i.e. “empLazy”. I am updating our app.component.ts file where we specified our routerLink HTML attribute value. Below is the updated code snippet for the same.
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'my-app',
- template: `<nav class="navbar navbar-inverse">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
- <span class="sr-only">Toggle navigation</span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- <a class="navbar-brand" href="#">{{orgName}}</a>
- </div>
- <div class="collapse navbar-collapse" id="navbar">
- <ul class="nav navbar-nav">
- <li><a routerLink="welcome" routerLinkActive="active">Home <span class="sr-only">(current)</span></a></li>
- <li><a routerLink="empLazy/emp-list" routerLinkActive="active">Emp-List</a></li>
- <li><a routerLink="empLazy/emp-info" routerLinkActive="active">E-Details</a></li>
- </ul>
- </div>
- </div>
- </nav>
- <div class='container'>
- <div class="col-md-7">
- <router-outlet></router-outlet>
- </div>
- <div class="col-md-5">
- <router-outlet name="detailsOutlet"></router-outlet>
- </div>
- </div>`
- })
- export class AppComponent {
- orgName: string = "Angular2 Series";
- }
NOTE
This time, we set the routerLink to “empLazy/emp-list” and “empLazy/emp-info” where empLazy will load our EmpModule.
- Create the routes configuration for the EmpModule. Here is the updated code snippet for the same: emp-route.config.ts file.
- import { Routes } from '@angular/router';
-
- import { EmployeeListComponent } from './emp-list.component'
- import { EmployeeDetailsComponent } from './emp-details.component';
- import { EmployeeInfoComponent } from './emp-info.component';
-
- export const eRoutes: Routes = [
- {
- path: 'emp-list',
- children: [
- { path: '', component: EmployeeListComponent },
- { path: 'emp-details/:eid', component: EmployeeDetailsComponent }
- ]
- },
- {
- path: 'emp-info',
- children: [
- { path: '', component: EmployeeInfoComponent },
- { path: 'emp-details/:eid', component: EmployeeDetailsComponent, outlet: "detailsOutlet" }
- ]
- }
- ]
- Update our EmpModule to load the Router configuration for the module using the “RouterModule.forChild() method”. Here is the updated code snippet for “emp-module.ts” file.
- import { NgModule } from '@angular/core';
- import { FormsModule } from '@angular/forms';
- import { RouterModule } from '@angular/router';
- import { CommonModule } from '@angular/common';
- import { EmployeeListComponent } from './emp-list.component';
- import { EmployeeSearchPipe } from './emp-search.pipe';
- import { FormatSalaryDirective } from './emp-formatsalary.directive';
- import { EmpService } from './emp.service';
- import { SharedModule } from '../shared/shared.module';
- import { EmployeeDetailsComponent } from './emp-details.component';
- import { EmployeeInfoComponent } from './emp-info.component';
- import { eRoutes } from './emp-route.config';
-
-
- @NgModule({
- imports: [CommonModule, FormsModule, SharedModule, RouterModule.forChild(eRoutes)],
- declarations: [EmployeeListComponent, EmployeeSearchPipe, FormatSalaryDirective, EmployeeDetailsComponent, EmployeeInfoComponent],
- providers: [EmpService],
- exports: [EmployeeListComponent, EmployeeDetailsComponent, EmployeeInfoComponent]
- })
- export class EmpModule {
- }
- Update our routerLink attribute for “emp-info.component.html” so that routing works in case of Auxiliary routes too. Here is the update code snippet for the same.
- <ul class="list-group" style="width:450px;">
- <li class="list-group-item" *ngFor="let id of eIds">
- <a [routerLink]="['/empLazy/emp-info',{outlets: {'detailsOutlet': ['emp-details',id]}}]">{{id}}</a>
- </li>
- </ul>
Try running the application and on landing of our home page, check network tab. You’ll only find that the resources required by the home page are loaded.
Below is the snapshot for the same.
Now, try clicking the EmpList or EDetails menu item. You’ll find that the EmpModule will get loaded as soon as you click on any of these links.
Our app is working as expected after implementing lazy loading. Try checking it.
On click of EmpId, you’ll be navigated to the EmployeeDetailsComponent. Below is the snap for the same.
On click of E-Details, you’ll be navigated to EmployeeInfoComponent.
Now that you know lazy loading you can further explore it. I am uploading the solution file with this post; but I won’t be able to upload the node_modules folder because of the heavy size. Thus, I request you to install NPM before you run the application.