Simple wrapper for Angular 9 lazy component loading using import
.
-
Install the lib
npm install ng-lazy-component
-
Import the
NgLazyComponentModule
from the lib into your module where you want to lazy load a component -
Use the
ng-lazy-component
in your template:<ng-lazy-component [loader]="componentLoader" [className]="componentName" [inputs]="inputs"> </ng-lazy-component>
Where the inputs are the following:
className: string; inputs: { [index: string]: any }; loader: () => Promise<any>;
Available outputs are:
componentOutput = new EventEmitter<LazyComponentOutput>(); componentInstance = new EventEmitter<any>();
LazyComponentOutput
type:export interface LazyComponentOutput { [index: string]: Observable<any>; }
Example:
componentLoader = () => import('./components/todo-list/todo-list.component'); componentName = 'TodoListComponent'; inputs = { listName: 'My Todo List', todos: [ 'Do homework', 'Walk the dog', 'Work', 'Repeat', ] };
This will load the component 'lazily' when the template is rendered.