JavaScriptAngularJSDynamically Lazy Load & Code-Split For Angular

Dynamically Lazy Load & Code-Split For Angular
D

Are you looking for a lazyload component for your Angular application. If so, in this article I will share a simple Angular lazy loading plugin that supports dynamic lazy loading. You can dynamically fetch images and integrate this dynamic lazy loadable component.

Installation

Install via npm;

npm i ngx-loadable-component

* unfortunately, only an aot build angular setup will work correctly within the loadable component setup 🤷 ️ .. an example of how this is setup can be seen within the base directory of this repo(app demo)

Setup

Create a component you wish to dynamically load… e.g. loadable component

upside-down-face-emoji.component.ts

@Component({
  selector: 'app-upside-down-face-emoji'
  ...
})
export class UpsideDownFaceEmojiComponent { }

* its important that this component does not use OnPush changeDetection as this will interfere with the loadable component setup

Then create a module for the loadable component:

upside-down-face-emoji.module.ts

import { LoadableComponentModule } from 'ngx-loadable-component';

import { UpsideDownFaceEmojiComponent } from './upside-down-face-emoji.component';

@NgModule({
  imports: [
    // register as loadable component
    LoadableComponentModule.forChild(UpsideDownFaceEmojiComponent)
  ],
  declarations: [UpsideDownFaceEmojiComponent]
})
export class UpsideDownFaceEmojiComponentModule {}

Create a manifest file which lists all your loadable components:

app-loadable.manifests.ts

import { LoadableManifest } from 'ngx-loadable-component';

export enum LoadableComponentIds {
  UPSIDE_DOWN_FACE = 'UpsideDownFaceEmojiComponent'
}

export const appLoadableManifests: Array<LoadableManifest> = [
  {
    // used to retrieve the loadable component later
    componentId: LoadableComponentIds.UPSIDE_DOWN_FACE,
    // must be a unique value within the app...
    // but apart from that only used by angular when loading component
    path: `loadable-${LoadableComponentIds.UPSIDE_DOWN_FACE}`,
    // relative path to component module
    loadChildren: './components/upside-down-face-emoji/upside-down-face-emoji.module#UpsideDownFaceEmojiComponentModule'
  }
];

Add the loadable component manifest & loadable component module to root app module:

app.module.ts

import { LoadableComponentModule } from 'ngx-loadable-component';

// loadable components manifest
import { appLoadableManifests } from './app-loadable.manifests';

@NgModule({
  declarations: [
      ...
  ],
  imports: [
    ...
    // components to load as seperate async
    LoadableComponentModule.forRoot(appLoadableManifests)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Be sure to import the loadable component module into any feature modules you use it in:

my-feature.module.ts

import { LoadableComponentModule } from 'ngx-loadable-component';

@NgModule({
  declarations: [
      ...
  ],
  imports: [
    ...
    LoadableComponentModule.forFeature()
  ]
})
export class MyFeatureModule { }

Usage (basic)

Add a loadable component where needed:

app.component.html

<div class="app--emojis">

    <loadable-component [componentId]="UPSIDE_DOWN_FACE_COMPONENT_ID" [loadComponent]="loadUpsideDownFaceComponent">
        <!-- any element in the loadable component content area will only be shown whilst loadComponent is false -->
        <app-placeholder-emoji></app-placeholder-emoji>
    </loadable-component>

</div>

app.component.ts

import { LoadableComponentIds } from '../../app-loadable.manifests';

@Component({ ... })
export class AppComponent {
  // loadable component ids
  UPSIDE_DOWN_FACE_COMPONENT_ID: string = LoadableComponentIds.UPSIDE_DOWN_FACE;

  // flags to load components
  // setting this to 'true' will cause the loadable component
  // to load the specified component id
  loadUpsideDownFaceComponent: boolean = false;
}

Usage (with Inputs/Outputs)

If our loadable component has inputs/outputs – like so:

upside-down-face-emoji.component.html

<a (click)="onClick()">
    <div>🙃</div>
    <div>{{ text }}</div>
</a>

upside-down-face-emoji.component.ts

export class UpsideDownFaceEmojiComponent {
  @Input() text: string = 'upside down';

  @Output() clicked: EventEmitter<string> = new EventEmitter<string>();

  constructor() {}

  onClick(): void {
    this.clicked.emit(this.text);
  }
}

We then create a model representing the inputs/outputs (for some typing goodness 💯):

upside-down-face-emoji.inputs.model.ts

import { LoadableComponentInputs } from 'ngx-loadable-component';

export interface UpsideDownFaceEmojiComponentInputs extends LoadableComponentInputs {
  text: string;
}

upside-down-face-emoji.outputs.model.ts

import { LoadableComponentOutputs } from 'ngx-loadable-component';

export interface UpsideDownFaceEmojiComponentOutputs extends LoadableComponentOutputs {
  clicked: Function;
}

And add our inputs/outputs to the loadable component wherever its used:

app.component.html

<div class="app--emojis">

    <loadable-component
        [componentId]="UPSIDE_DOWN_FACE_COMPONENT_ID"
        [loadComponent]="loadUpsideDownFaceComponent"
        [componentInputs]="upsideDownFaceInputs"
        [componentOutputs]="upsideDownFaceOutputs">
        <!-- any element in the loadable component content area will only be shown whilst loadComponent is false -->
        <app-placeholder-emoji></app-placeholder-emoji>
    </loadable-component>

</div>

app.component.ts

import { LoadableComponentIds } from '../../app-loadable.manifests';
import { UpsideDownFaceEmojiComponentInputs } from '../../components/upside-down-face-emoji/models/upside-down-face-emoji.inputs.model';
import { UpsideDownFaceEmojiComponentOutputs } from '../../components/upside-down-face-emoji/models/upside-down-face-emoji.outputs.model';

@Component({ ... })
export class AppComponent {
  // loadable component ids
  UPSIDE_DOWN_FACE_COMPONENT_ID: string = LoadableComponentIds.UPSIDE_DOWN_FACE;

  // flags to load components
  // setting this to 'true' will cause the loadable component
  // to load the specified component id
  loadUpsideDownFaceComponent: boolean = false;

  // inputs for loadable component
  get upsideDownFaceInputs(): UpsideDownFaceEmojiComponentInputs {
    return {
      text: 'not upside down'
    }
  }

  // outputs for loadable component
  get upsideDownFaceOutputs(): UpsideDownFaceEmojiComponentOutputs {
    return {
      clicked: (text: string) => this.onClickedUpsideDownFace(text)
    }
  }

  onClickedUpsideDownFace(text: string): void {
    console.log('🖱', text);
  }
}

And voila! we now have input/output binding 👌. * note that the inputs in the parent component (of the loadable component – e.g. upsideDownFaceInputs()) have to be within a getter or function for change detection to apply correctly

Usage (add custom css classes)

Custom css classes can be passed via the loadable component componentCssClasses input. These will be added to the host element of the provided loadable component. e.g.

app.component.html

<div class="app--emojis">

    <loadable-component ... [componentCssClasses]="customCssClasses" >
        ...
    </loadable-component>

</div>

app.component.ts

@Component({ ... })
export class AppComponent {
  ...
  // custom css classes
  customCssClasses: Array<string> = ['my-custom--class--1', 'my-custom--class--2']
  ...
}

See the demo and download the source code.

This awesome script developed by dan-harris. Visit their official repository for more information and follow for future updates.

Saroj Meher
Saroj Meherhttps://www.sarojmeher.com
Howdy! Friends, I am Saroj Meher. I am an Artist. I do Painting on mediums like Acrylic, Watercolour, Oil etc. I have over 7 years of experience in WordPress. I am currently running 30+ website. I am specialized in WordPress and WooCommerce, WordPress Theme Customization and Theme Development. I can fix any kind of WordPress error/issue like PHP, CSS, Js issues and other Theme and Plugin related issues. Client's Satisfaction is my first priority.

Subscribe For More!

Subscribe to get the Latest Updates directly in you Email box.

Explore More

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

SAROJMEHER Photograph
I am a Lecturer (English & Sociology), a professional Artist, and a blogger. I do painting, sketches since my childhood. I am in the teaching for 10 years. In this teaching line, I have experience in teaching English at High School and College levels. I have also experienced teaching computer theory during the school teaching period. This is my personal web corner over the internet.

Quick Guides

7 Simple Steps To Start Your Blogging Journey

TRENDING TOPICS