ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Guide to Lazy loading in Angular

Lazy loading is the technique where angular loads the Modules only on a need basis rather than all at once. It is also called on-demand loading. By default, Angular Loads the modules eagerly. Lazy Loading of Angular Modules reduces the initial load time of the app. We use the loadChilden method of the Angular Router to lazy load them when the user navigates to a route. In this article, we will show you how to implement lazy loading

Why Lazy load?

The Angular apps get bigger in size as we add more and more features. The Angular Modules help us to manage our app by creating separate modules for each new feature. But, as the app gets bigger in size, slower it loads. That is because of angular loads the entire application upfront.

The slow loading app does not leave a good impression on the user. By Loading only a part of the app (i.e lazy loading), the app appears to run faster to the user. The faster loading app gives you a performance boost and also results in a good user experience.

How Lazy loading works

In Angular, the Lazy loading works at the module level. i.e. you can lazy load only the Angular Modules. We cannot lazy load the Individual components.

The Lazy loading works via the Angular Router Module. The loadChildren method of the Angular Router is responsible to load the Modules

We define the modules which we want to lazy load, when we define the routes. Starting from the Angular 8, we have a new syntax for lazy loading.

                              
 
 {path: "admin", loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)},
 
                            
                        

The admin is the path is the URL path segment to the AdminModule. The loadChildren is where we configure the Lazy Loading.

loadChildren

We need to provide call back function to loadChildren argument. The call back must load the AdminModule. We use the dynamic import syntax using the import method. The import method loads the module from the path, which we provide as the argument to it.

                              

import('./admin/admin.module').then(m => m.AdminModule)
                            
                        

When the user navigates to the admin URL or to any of its child routes like admin/dashboard, the router will fetch the AdminModule and loads the routes and components of the AdminModule

The lazy loaded module loads only for the first visit of the URL, it will not load when we revisit that URL again.

When we define an AdminModule to lazy loaded, the angular creates a separate bundle for the entire module.

Angular Lazy Loading Example

Let us build a simple app. The app will have two modules. One is SharedModule which we load eagerly. The other module is AdminModule. First, we load the AdminModule eagerly and later we we update it to use the Lazy Loading.

Admin Module

The AdminModule contains three components DashboardComponent, RightsComponent; UserComponent. The Module contains, three routes defined as children of Admin Route defined in the AdminRoutingModule

                              
 
{  path: 'admin',
        children :[
            { path: 'dashboard', component: DashboardComponent},
            { path: 'user', component: UserComponent},
            { path: 'rights', component: RightsComponent},
        ]
    },
 
                            
                            

The above routes are registered using the forChild method()

The Complete source code of AdminModule is as below

src/app/admin/pages/dashboard/dashboard.component.ts
                              

  import { Component } from '@angular/core';
 
  @Component({
    template: `<h1>Dashboard Component</h1>`,
  })
  export class DashboardComponent {
    title = '';
  }
 
                            
                        
src/app/admin/pages/rights/rights.component.ts
                              

import { Component } from '@angular/core';
 
@Component({
  template: '<h1>Rights Component</h1>',
})
export class RightsComponent {
  title = '';
}
 
                            
                        
src/app/admin/pages/user/user.component.ts
                              
 
import { Component } from '@angular/core';
 
@Component({
  template: '<h1>User Component</h1>',
})
export class UserComponent {
  title = '';
}
 
                            
                        
src/app/admin/pages/index.ts
                              

export * from './dashboard/dashboard.component';
export * from './rights/rights.component';
export * from './user/user.component';
 
                            
                        
src/app/admin/admin.routing.module.ts
                              

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 
import { UserComponent , RightsComponent ,DashboardComponent } from './pages';
 
const routes: Routes = [
    {  path: 'admin',
        children :[
            { path: 'dashboard', component: DashboardComponent},
            { path: 'user', component: UserComponent},
            { path: 'rights', component: RightsComponent},
        ]
    },
];
 
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }
 
 
                            
                        
src/app/admin/admin.module.ts
                              

import { NgModule } from '@angular/core';
 
import { AdminRoutingModule } from './admin.routing.module';
import { UserComponent,RightsComponent,DashboardComponent } from './pages';
 
 
@NgModule({
  declarations: [UserComponent,RightsComponent,DashboardComponent],
  imports: [
    AdminRoutingModule,
  ],
  providers: [],
})
export class AdminModule { }

                            
                        
                              

export * from './admin.module';
export * from './pages';
                            
                        

Shared Module

The SharedModule contains HeaderComponent & FooterComponent. The HeaderComponent contains the navigation menu.

src/app/shared/layout/footer/footer.component.ts
                              

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html'
})
export class FooterComponent {
}
 
                            
                        
src/app/shared/layout/footer/footer.component.html
                              
 
<p>(c) All Rights Reserved</p>
                            
                        
src/app/shared/layout/header/header.component.ts
                              
 
import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent {
}
                            
                        
/app/shared/layout/footer/footer.component.ts
                              

<ul>
    <li>
      <a class="navbar-brand" routerLink="">home</a>
    </li>
    <li>
      <a class="navbar-brand" routerLink="/admin/dashboard">Dashboard</a>
    </li>
    <li>
      <a class="navbar-brand" routerLink="/admin/rights">rights</a>
  </li>
  <li>
    <a class="navbar-brand" routerLink="/admin/user">user</a>
  </li>
</ul>
 
                            
                        
src/app/shared/layout/header/header.component.css
                              
 
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333333;
}
 
li {
    float: left;
}
 
li a {
    display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}
 
li a:hover {
    background-color: #111111;
}
                            
                        
src/app/shared/layout/index.ts
                              

export * from './footer/footer.component';
export * from './header/header.component';
                            
                        
src/app/shared/shared.module.ts
                              
 
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { HeaderComponent, FooterComponent } from './layout';
 
 
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    RouterModule
  ],
  declarations: [ HeaderComponent,FooterComponent ],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    RouterModule,
    HeaderComponent,FooterComponent
  ]
})
export class SharedModule {
}
 
 
                            
                        
src/app/shared/index.ts
                              
 
export * from './shared.module';
export * from './layout';
 
                            
                        

Root Module

The Root Module uses the forRoot method to register the routes. Right now it does not contain any routes. It also imports the AdminModule

                              

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

<app-header></app-header>
 
<h1>Lazy loaded module Demo</h1>
 
<router-outlet></router-outlet>
<app-footer></app-footer>
 
                            
                        
                              
 
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 
const routes: Routes = [
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
                            
                        
                              

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
 
import { AppComponent } from './app.component';
import { SharedModule} from './shared';
import { AdminModule} from './admin';
 
@NgModule({
  declarations: [
    AppComponent, 
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    SharedModule,
    AdminModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
 
                            
                        

Test the app by running it.

When you run the ng Serve command, you will see that it generates the five JavaScript files ( called chunks) main.js,polyfills.js,runtime.js,styles.js,vendor.js. As you add more and more features those are added to the main.js file

image

Ctrl + Shift + I to open the chrome developer console and and open the network tab. Run the app and you will see that all the chunks are loaded upfront

image

Lazy loading the AdminModule

To Lazy Load AdminModule, First we need to add the following route in the AppRoutingModule. This route instructs the router load the AdminModule from the path ./admin/admin/module.ts when user navigates to the Admin route

                              

const routes: Routes = [
  {path: "admin", loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)},
];
 
                            
                        

Next, we need to remove the import of AdminModule from the AppModule. If you did not do it, the module will be loaded eagerly.

Finally, We need to change the route definition in the AdminRoutingModule. We have removed the parent route admin as it is now moved to the AppRoutingModule. Since this is a lazy-loaded module, the routes we specify will automatically become the child route of admin

                              

const routes: Routes = [
    { path: 'dashboard', component: DashboardComponent},
    { path: 'user', component: UserComponent},
    { path: 'rights', component: RightsComponent},
];
 
                            
                        

Now, when you run ng serve command, you will notice the admin-admin.module.js file. The Angular compiler generates a separate js file for each lazy loaded module. This file is loaded only when it is needed by the router.

image

You can test it by running the app. You can notice that admin-admin.module.js is not loaded when you run the app. It is loaded only when you click either on Dashboard, user or rights menu.

image

Services in Lazy Loaded Module

We need to be careful when we create a service or provide a services in Lazy loaded module.

Any Service defined in the Lazy Loaded Module, will not be load until the user navigates to that module. Hence we cannot use them anywhere else in the application.

The Angular creates a separate injector for the lazy loaded module. Therefore, any service we provide in the lazy loaded module gets its own instance of the service.

Hence create a service in the lazy loaded module, only if it is used within the lazy loaded Module. Else consider moving it to the AppModule or a special CoreModule. For More read Folder structure in Angular

Dos and Dont’s of Lazy loaded Modules

Do not import lazy loaded modules in any other modules. This will make the angular to load the module eagerly and can have unexpected bugs.

Be careful when you import other modules in the lazy loaded module. If the other modules providers any services, then the lazy loaded module will get a new instance of the service. This may have unintended side effects, if the services are intended to be app-wide singleton

Summary

The Angular Modules and lazy loading of those modules is one of the best features of angular. You should load only the SharedModule & CoreModule upfront and lazy load rest of the application.