Angular动态加载组件

绝地灬酷狼 2022-02-23 02:42 637阅读 0赞

引言

有时候需要根据URL来渲染不同组件,我所指的是在同一个URL地址中根据参数的变化显示不同的组件;这是利用Angular动态加载组件完成的,同时也会设法让这部分动态组件也支持AOT。

动态加载组件

下面以一个Step组件为示例,完成一个3个步骤的示例展示,并且可以通过URL user?step=step-one 的变化显示第N个步骤的内容。

1、resolveComponentFactory

首先,还是需要先创建动态加载组件模块。

  1. import { Component, Input, ViewContainerRef, ComponentFactoryResolver, OnDestroy, ComponentRef } from '@angular/core';
  2. @Component({
  3. selector: 'step',
  4. template: ``
  5. })
  6. export class Step implements OnDestroy {
  7. private currentComponent: ComponentRef<any>;
  8. constructor(private vcr: ViewContainerRef, private cfr: ComponentFactoryResolver) {}
  9. @Input() set data(data: { component: any, inputs?: { [key: string]: any } } ) {
  10. const compFactory = this.cfr.resolveComponentFactory(data.component);
  11. const component = this.vcr.createComponent(compFactory);
  12. if (data.inputs) {
  13. for (let key in data.inputs) {
  14. component.instance[key] = data.inputs[key];
  15. }
  16. }
  17. this.destroy();
  18. this.currentComponent = component;
  19. }
  20. destroy() {
  21. if (this.currentComponent) {
  22. this.currentComponent.destroy();
  23. this.currentComponent = null;
  24. }
  25. }
  26. ngOnDestroy(): void {
  27. this.destroy();
  28. }
  29. }

抛开一销毁动作不谈的话,实际就两行代码:

  1. let compFactory = this.cfr.resolveComponentFactory(this.comp);

利用 ComponentFactoryResolver 查找提供组件的 ComponentFactory,而后利用这个工厂来创建实际的组件。

  1. this.compInstance = this.vcr.createComponent(compFactory);

这一切都非常简单。

而对于一些基本的参数,是直接对组件实例进行赋值。

  1. for (let key in data.inputs) {
  2. component.instance[key] = data.inputs[key];
  3. }

最后,还需要告诉Angular AOT编译器为用户动态组件提供工厂注册,否则 ComponentFactoryResolver 会找不到它们,最简单就是利用 NgModule.entryComponents 进行注册。

  1. @NgModule({
  2. entryComponents: [ UserOneComponent, UserTwoComponent, UserThirdComponent ]
  3. })
  4. export class AppModule { }

但这样其实还是挺奇怪的,entryComponents 本身可能还会存在其他组件。而动态加载组件本身是一个通用性非常强,因此,把它封装成名曰 StepModule 挺有必要的,这样的话,就可以创建一种看起来更舒服的方式。

  1. @NgModule({
  2. declarations: [ Step ],
  3. exports: [ Step ]
  4. })
  5. export class StepModule {
  6. static withComponents(components: any) {
  7. return {
  8. ngModule: StepModule,
  9. providers: [
  10. { provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: components, multi: true }
  11. ]
  12. }
  13. }
  14. }

通过利用 ANALYZE_FOR_ENTRY_COMPONENTS 将多个组件以更友好的方式动态注册至 entryComponents

  1. const COMPONENTS = [ ];
  2. @NgModule({
  3. declarations: [ ...COMPONENTS ],
  4. imports: [
  5. StepModule.withComponents([ ...COMPONENTS ])
  6. ]
  7. })
  8. export class AppModule { }

2、一个示例

有3个Step步骤的组件,分别为:

  1. // user-one.component.ts
  2. import { Component, OnDestroy, Input, Injector, EventEmitter, Output } from '@angular/core';
  3. @Component({
  4. selector: 'step-one',
  5. template: `<h2>Step One Component:params value: {
  6. {step}}</h2>`
  7. })
  8. export class UserOneComponent implements OnDestroy {
  9. private _step: string;
  10. @Input()
  11. set step(str: string) {
  12. console.log('@Input step: ' + str);
  13. this._step = str;
  14. }
  15. get step() {
  16. return this._step;
  17. }
  18. ngOnInit() {
  19. console.log('step one init');
  20. }
  21. ngOnDestroy(): void {
  22. console.log('step one destroy');
  23. }
  24. }

user-two、user-third 略同,这里组件还需要进行注册:

  1. const STEPCOMPONENTS = [ UserOneComponent, UserTwoComponent, UserThirdComponent ];
  2. @NgModule({
  3. declarations: [ ...STEPCOMPONENTS ],
  4. imports: [
  5. StepModule.withComponents([ ...STEPCOMPONENTS ])
  6. ]
  7. })
  8. export class AppModule { }

这里没有 entryComponents 字眼,而是为 StepModule 模块帮助我们动态注册。这样至少看起来更内聚一点,而且并不会与其他 entryComponents 在一起,待东西越多越不舒服。

最后,还需要 UserComponent 组件来维护步骤容器,会根据 URL 参数的变化,利用 StepComponent 组件动态加载相应组件。

  1. @Component({
  2. selector: 'user',
  3. template: `<step [comp]="stepComp"></step>`
  4. })
  5. export class UserComponent {
  6. constructor(private route: ActivatedRoute) {}
  7. stepComp: any;
  8. ngOnInit() {
  9. this.route.queryParams.subscribe(params => {
  10. const step = params['step'] || 'step-one';
  11. // 组件与参数对应表
  12. const compMaps = {
  13. 'step-one': { component: UserOneComponent, inputs: { step: step } },
  14. 'step-two': { component: UserTwoComponent },
  15. 'step-third': { component: UserThirdComponent },
  16. };
  17. this.stepComp = compMaps[step];
  18. });
  19. }
  20. }

非常简单的使用,而且又对AOT比较友好。

总结

文章里面一直都在提AOT,其实AOT是Angular为了提供速度与包大小而生的,按我们项目的经验来看至少在包的大小可以减少到 40% 以上。

当然,如果你是用angular cli开发,那么,当你进行 ng build --prod 的时候,默认就已经开启 AOT 编译模式。

发表评论

表情:
评论列表 (有 0 条评论,637人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Angular动态组件

    引言 有时候需要根据URL来渲染不同组件,我所指的是在同一个URL地址中根据参数的变化显示不同的组件;这是利用Angular动态加载组件完成的,同时也会设法让这部分动态组

    相关 Angular

    1.什么是懒加载呢?   一个应用在启动的时候,有些模块根本就用不上,比如说:打开淘宝,默认的主窗口是商品列表及图片等信息,这个时候就不需要加载支付模块了,因此对于支付模块就