angular动态组件探坑之旅

angular动态组件有两种创建方式,这篇只说一种,用大白话讲,就是先把要用到的各种组件提前写好,然后在需要的地方动态调用。

第一步:先准备若干要用到的组件,直接上图(因为这儿需要传递参数,所以组件中会有input指令)

这儿只是个简单例子,可以理解为component A,既然是动态组件,肯定会有B、C、D。。。。

第二步:编写动态模块容器,

/**
 * Created by NewBee on 2018/7/2.
 */
import {Component,ViewChild, Input, ViewContainerRef, ComponentFactoryResolver,OnInit, OnDestroy, ComponentRef, ChangeDetectorRef} from '@angular/core';
import {CpuComponent} from './cpu/cpu.component';
import {MemComponent} from './mem/mem.component';
import {DY1Component} from './DY1Component';

@Component({
    selector: 'dynamic',
    template: ``
})
export class DynamicCom implements OnInit, OnDestroy{

    @Input() inputs:any;         //加载组件需要传入的参数组

    @Input() component:any;     //需要加载的组件名

    private currentComponent: ComponentRef<any>;
    
    comps: any ;

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

    ngOnInit() {
        if(this.component == 'cpu'){
            this.comps = CpuComponent;
        }else if(this.component == 'mem'){
            this.comps = MemComponent;
        }else{
            this.comps = DY1Component;
        }
    }

    loadComponent() {

        let com = this.cfr.resolveComponentFactory(this.comps);
        this.vcr.clear();
        let component = this.vcr.createComponent(com);
        if(!this.inputs){
            this.inputs={}
        }else{
            for (let key in this.inputs) {
                component.instance[key] = this.inputs[key];
            }
        }
        this.destroy();
        this.currentComponent = component;
    }

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

    ngAfterViewInit() {

        setTimeout(() => this.loadComponent(),0);//settimeout解决开发环境变更检测报错(多检测了一次)

    }

    ngOnDestroy() {
        this.destroy();
    }
}

上述代码如果不是因为传参缘故,真正有用的就两行,即

loadComponent()方法中的:
  let com = this.cfr.resolveComponentFactory(this.comps);
let component = this.vcr.createComponent(com);

传参:

component.instance[key] = this.inputs[key];

第三步:想要使用动态组件,必须先将componentA、B、C、D等声明到这些组件的子根module的entryComponents中,如图:

第四步:调用动态组件容器,显示动态组件;

<dynamic *ngFor="let temp of temps" [component]="temp.item" [inputs]="{'internal':alias,'size':temp.size}"></dynamic>

以上就是所有,当然其中还有很多坑,比如

由于angular的变更检测机制,如果直接调用loadComponent方法,开发环境会莫名其妙的报错,


查了下,说是生产环境下这个错误就不会有了,但是强迫症患者,只能把它解决掉,加上setTimeout完美解决。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值