import {Component, OnChanges, OnInit, Input, NgModule, NgModuleFactory, Compiler, SimpleChanges} from '@angular/core' ;
import { BaseModule } from "../module/BaseModule" ;
@Component ({
selector : 'dynamic' ,
template : `
<ng-container *ngComponentOutlet=" dynamicComponent ; ngModuleFactory: dynamicModule ;"></ng-container>`
})
export class DynamicCom {
dynamicComponent : any ;
dynamicModule : NgModuleFactory<any >;
@Input ('html' )
html : string ;
@Input ('list' )
list : any ;
constructor (private compiler: Compiler) {
}
ngOnChanges (changes: SimpleChanges) {
if (changes['html' ] && !changes['html' ].isFirstChange () || (changes['list' ] && !changes['list' ].isFirstChange ())) {
this .dynamicComponent = this .createNewComponent (this .html , this .list );
this .dynamicModule = this .compiler.compileModuleSync (this .createComponentModule (this .dynamicComponent ));
}
}
ngOnInit () {
this .dynamicComponent = this .createNewComponent (this .html , this .list );
this .dynamicModule = this .compiler.compileModuleSync (this .createComponentModule (this .dynamicComponent ));
}
protected createComponentModule (componentType: any ) {
@NgModule ({
imports : [BaseModule],
declarations : [
componentType
],
entryComponents : [componentType]
})
class RuntimeComponentModule {
}
// a module for just this Type
return RuntimeComponentModule;
}
protected createNewComponent (template: string , list: any ) {
@Component ({
selector : 'dynamic-component' ,
template : template ? template : '<div></div>'
})
class MyDynamicComponent {
public list : any = list;
}
return MyDynamicComponent;
}
}
使用:
1、引入组件< dynamic [html]= " html " [list]= " list " ></ dynamic > 2、定义html和数据 public list : Array<any > = ["aa" , "bb" , "cc" ];
public html = `<div>
<i>2w2w</i>
<ul>
<li *ngFor="let item of list; index as index">{{item}}</li>
</ul>
</div>` ;
参考:
https://embed.plnkr.co/9L72KpobVvY14uiQjo4p/