Angular动态加载组件

引言

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

动态加载组件

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

一、resolveComponentFactory

首先,仍是须要先建立动态加载组件模块。ui

import { Component, Input, ViewContainerRef, ComponentFactoryResolver, OnDestroy, ComponentRef } from '@angular/core';
@Component({
  selector: 'step',
  template: ``
})
export class Step implements OnDestroy {
  private currentComponent: ComponentRef<any>;

  constructor(private vcr: ViewContainerRef, private cfr: ComponentFactoryResolver) {}

  @Input() set data(data: { component: any, inputs?: { [key: string]: any } } ) {
      const compFactory = this.cfr.resolveComponentFactory(data.component);
      const component = this.vcr.createComponent(compFactory);
      if (data.inputs) {
        for (let key in data.inputs) {
          component.instance[key] = data.inputs[key];
        }
      }
      this.destroy();
      this.currentComponent = component;
  }

  destroy() {
    if (this.currentComponent) {
      this.currentComponent.destroy();
      this.currentComponent = null;
    }
  }
  
  ngOnDestroy(): void {
    this.destroy();
  }

}

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

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

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

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

这一切都很是简单。component

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

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

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

@NgModule({
  entryComponents: [ UserOneComponent, UserTwoComponent, UserThirdComponent ]
})
export class AppModule { }

但这样其实仍是挺奇怪的,entryComponents 自己可能还会存在其余组件。而动态加载组件自己是一个通用性很是强,所以,把它封装成名曰 StepModule 挺有必要的,这样的话,就能够建立一种看起来更舒服的方式。get

@NgModule({
  declarations: [ Step ],
  exports: [ Step ]
})
export class StepModule {
  static withComponents(components: any) {
    return {
      ngModule: StepModule,
      providers: [
        { provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: components, multi: true }
      ]
    }
  }
}

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

const COMPONENTS = [  ];

@NgModule({
  declarations: [ ...COMPONENTS ],
  imports: [
    StepModule.withComponents([ ...COMPONENTS ])
  ]
})
export class AppModule { }

二、一个示例

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

// user-one.component.ts
import { Component, OnDestroy, Input, Injector, EventEmitter, Output } from '@angular/core';
@Component({
  selector: 'step-one',
  template: `<h2>Step One Component:params value: {{step}}</h2>`
})
export class UserOneComponent implements OnDestroy {
  private _step: string;
  @Input() 
  set step(str: string) {
    console.log('@Input step: ' + str);
    this._step = str;
  }
  get step() {
    return this._step;
  }
  
  ngOnInit() {
    console.log('step one init');
  }
  ngOnDestroy(): void {
    console.log('step one destroy');
  }

}

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

const STEPCOMPONENTS = [ UserOneComponent, UserTwoComponent, UserThirdComponent ];

@NgModule({
  declarations: [ ...STEPCOMPONENTS ],
  imports: [
    StepModule.withComponents([ ...STEPCOMPONENTS ])
  ]
})
export class AppModule { }

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

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

@Component({
  selector: 'user',
  template: `<step [comp]="stepComp"></step>`
})
export class UserComponent {
  constructor(private route: ActivatedRoute) {}
  stepComp: any;
  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      const step = params['step'] || 'step-one';
      // 组件与参数对应表
      const compMaps = {
        'step-one': { component: UserOneComponent, inputs: { step: step } },
        'step-two': { component: UserTwoComponent },
        'step-third': { component: UserThirdComponent },
      };
      this.stepComp = compMaps[step];
    });
  }
}

很是简单的使用,并且又对AOT比较友好。

总结

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

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

相关文章
相关标签/搜索