angular使用动态加载的方式,处理差异化

一、背景

有些功能是差异化的,某些场景下需要,某些场景下不需要,因此想使用动态加载的方式处理这种场景。

二、解决方式

主要通过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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值