angular2 动态组件 dynamicCom

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/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值