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完美解决。