一、背景
有些功能是差异化的,某些场景下需要,某些场景下不需要,因此想使用动态加载的方式处理这种场景。
二、解决方式
主要通过angular提供的ViewContainerRef, ComponentFactoryResolver来实现。
1、提供app-dynamic-add-components组件
import {Component, Input, ViewContainerRef, ComponentFactoryResolver, OnDestroy, ComponentRef} from '@angular/core'; @Component({ selector: 'app-dynamic-add-components', template: `` }) export class DynamicAppComponentsComponent implements OnDestroy { private currentComponent: ComponentRef<any>; constructor(private vcr: ViewContainerRef, private cfr: ComponentFactoryResolver) { } @Input() set component(data: { component: any, inputs?: { [key: string]: any } }) { if (!data || !data.component) { this.destroy(); return; } const compFactory = this.cfr.resolveComponentFactory(data.component); const component = this.vcr.createComponent(compFactory); if (data.inputs) { for (const 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(); } }
import {ANALYZE_FOR_ENTRY_COMPONENTS, NgModule} from '@angular/core'; import { DynamicAppComponentsComponent } from './dynamic.add.components.component'; @NgModule({ declarations: [DynamicAppComponentsComponent], exports: [DynamicAppComponentsComponent] }) export class DynamicModule { static withComponents(components: any) { return { ngModule: DynamicModule, providers: [ {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: components, multi: true} ] }; } }
2、在路由模块导入 DynamicModule,DERSCRIBECOMPONENTS是需要动态处理的组件。
const DERSCRIBECOMPONENTS = [ HeaderNotifyComponent, ]; @NgModule({ imports: [ DynamicModule.withComponents([ ...DERSCRIBECOMPONENTS])], providers: [], declarations: [...DERSCRIBECOMPONENTS], exports: [], })
3、使用方式
// ts模块进行赋值 alertComponent = { component: HeaderNotifyComponent, // 需要动态加载的模块 inputs: { nzTitle: '告警' } // 给模块传的参数 } // html引入动态组件 <app-dynamic-add-components nz-tooltip [component]="alertComponent"></app-dynamic-add-components>
参考:https://segmentfault.com/a/1190000009582289#articleHeader2