Is there a way to lazy load components, not module

2020-06-30 11:30发布

问题:

Lazy loading is a commonly used technique. However, in Angular it seems that the granularity level of this technique stops at the module level.

That means that you can have module main that loads in the browser, and then on special occasion module B and C and D can be loaded lazily.

Almost all tutorials on web explain that. However, is there a way to load components lazily?

Consider this simple example that user goes inside the application, and when clicks "invoices" link, URL changes to the new route /invoice/list and a progress bar shows loading, while the invoices component including HTML and JS is being loaded inside the browser, is registered dynamically with the main module, and is being shown in the relevant outlet. Is that possible with Angular?

回答1:

Lazy loading a component is not possible. Reason for this behavior is the structure of angular. Components in angular have to be part of a module. Angular module is a container where you define all the components, services, pipes e.t.c. present inside. While building the application dist, all the dependencies declared in the module are included to make a chunk (transpiled js code). All the directly imported modules together form the main chunk whereas modules marked as lazily loaded form a separate chunk that sits on the server untill the respective route is hit and a call for it is made from the client. Now components do not form a chunk and hence it is not possible



回答2:

Currently (Angular 8 timeframe) there are two 3rd party libraries that make lazy-loading of components easier:

  • ngx-loadable: https://github.com/mohammedzamakhan/ngx-loadable
  • hero-loader: https://www.npmjs.com/package/@herodevs/hero-loader

Note: both of these libraries are built upon NgModuleFactoryLoader, which is deprecated in Angular 8, but there is no alternative yet ... 


  • Class marked as deprecated: https://angular.io/api/core/NgModuleFactoryLoader 

  • Explanation of Rob Wormald of the Angular Team: https://twitter.com/robwormald/status/1143981312237137925

The Angular team has announced that lazy loading of components should become easier with Ivy (Angular 9?), but it is not clear yet how this will look like...



回答3:

A bit hacky ... but possible (future versions of Angular (beyond ver. 7) will implement an easier apporach)

https://blog.angularindepth.com/dynamically-loading-components-with-angular-cli-92a3c69bcd28



回答4:

Update, with Angular 9 and Ivy it is possible and relatively easy. First of all you need to have some anchor in your app where you want to load your component, it could be named templateRef if you want multiple different components at the same time or ng-template for single one. To do that (i will use ng-template) in your component.html:

<ng-template>

component.ts:

export class ExampleComponent {
    @ViewChild(TemplateRef, { read: ViewContainerRef })
    private anchorRef: ViewContainerRef;

    constructor(
        private readonly componentFactoryResolver: ComponentFactoryResolver
    ) {}

    private async loadComponent() {
        this.anchorRef.clear(); // clear if some components are already there
        const { component } = await import(
            'path to your component'
        );
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
            component
        );
        // We could attach @Input and react to @Output by using below instance if needed.
        // Remember we should handle the ngOnChanges lifecycle hook.
        // For that implementation needed.
        this.anchorRef.createComponent(componentFactory);
    }
}

All that is left is basically call loadComponent when it's needed;

If you need some modules, for ex you want to use Angular Material. You need to create simple ngModule without export inside your lazyLoaded component. Like this:

@Component({...})
export class Component implements OnInit {
    constructor() {}

    ngOnInit() {}
}

@NgModule({
    declarations: [Component],
    imports: [MatIconModule],
})
class TasksListModule {}

Also, you could follow the approach Angular team has in their documentation: https://angular.io/guide/dynamic-component-loader