With Angular Standalone APIs (launched in v14) it’s doable to manually lazy load a element (even with it’s dependency providers and suppliers), equally to how we might manually lazy load a NgModule
. We simply must create ourselves a baby EnvironmentInjector
(simulating what a lazy-loaded NgModule
would do). That is additionally precisely what the Angular Router
does since v14, when instantiating a element for a Route
that has it is personal suppliers
array.
TLDR: See the stackblitz instance of manually lazy loading a element with a service, with Standalone APIs.
For instance, as an example we’ve a barrel index.ts
with gadgets that we need to lazy load all collectively – a element and a service. And let’s suppose the element is dependent upon the service.
// lazy/index.ts
export * from './lazy.service';
export * from './lazy.element';
// customized naming conference - export an array named `suppliers`:
export const suppliers = [LazyService];
Then we will lazy load this barrel and create a baby EnvironmentInjector
(containing all barrel’s suppliers
). In a while this injector can be utilized when instantiating the lazy element (so the element has the entry to the suppliers
talked about above).
export class AppComponent {
constructor(
protected viewContainerRef: ViewContainerRef,
protected injector: Injector,
protected environmentInjector: EnvironmentInjector
) {}
lazyLoadComponent() {
// 1. lazy load the barrel file
import('./lazy/index').then((lazyBarrel) => {
// 2. create manually an `EnvironmentInjector` with all
// the `suppliers` exported from the lazy barrel.
// Move `this.environmentInjector` as a father or mother.
const childEnvironmentInjector = createEnvironmentInjector(
lazyBarrel.suppliers,
this.environmentInjector,
'Lazy Atmosphere Injector'
);
// 3. instantiate a lazy element, passing:
// the father or mother element's component `Injector`
// and the simply created little one `EnvironmentInjector`
const lazyComponent = createComponent(lazyBarrel.LazyComponent, {
environmentInjector: childEnvironmentInjector,
elementInjector: this.injector,
});
// 4. connect the lazy element contained in the father or mother element
this.viewContainerRef.insert(lazyComponent.hostView);
});
}
Routing-driven lazy loading – Angular 14 supply code evaluation
The above method is similar to how the Angular Router
instantiates parts (not solely lazy-loaded) underneath the hood, since model 14. When matching an URL towards a Route
that comprises an array of suppliers
, Angular creates a baby EnvironmentInjector
. In a while, when the <router-outlet>
instantiates a element for the present Route
, Angular takes the Route
‘s EnvironmentInjector
(or the closest injector outlined within the father or mother Routes
) after which it makes use of this EnvironmentInjector
when making a element occasion, so the element has entry to the Route
‘s suppliers
.