Dynamic Imports with Angular Universal
Illustrate how to use dynamic imports in Angular Universal to lazy-load server-side modules and improve performance.
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
@Component({
selector: 'app-lazy',
template: `<button (click)="loadModule()">Load Lazy Module</button>`
})
export class LazyComponent implements OnInit {
constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
async loadModule() {
// Ensure we're in the browser before lazy-loading
if (isPlatformBrowser(this.platformId)) {
const { LazyModule } = await import('./lazy/lazy.module').then(m => m);
// Use the imported module, e.g., for manual bootstrapping
console.log('Lazy module loaded:', LazyModule);
}
}
ngOnInit(): void {
// Initial component logic...
}
}
This code defines an Angular component called `LazyComponent` with a button to trigger lazy-loading of a module named `LazyModule`. The `loadModule` function checks if the code is running in the browser using `isPlatformBrowser` since Angular Universal applications render on the server as well. If in the browser, it dynamically imports the `LazyModule` using the `import()` function and handles the promise with a `then` block. The module can then be used or bootstraped as required.