将依赖项添加到动态创建的角度组件

时间:2017-07-12 06:55:25

标签: angular typescript

我在运行时使用JitCompiler创建和编译角度组件,下面是我的代码。

import { Component, OnInit, Compiler, Injector, NgModuleRef, NgModule, ViewChild, ViewContainerRef } from '@angular/core';

@Component({
    selector: 'web-application',
    templateUrl: 'creator.component.html'
})

export class CreatorComponent implements OnInit {

    result: any;
    @ViewChild('newCreatedComponent', { read: ViewContainerRef }) newCreatedComponent: ViewContainerRef;

    constructor(
        private _compiler: Compiler,
        private _injector: Injector,
        private _m: NgModuleRef<any>) { }
    ngOnInit() {
    }
    ngAfterViewInit() {

        const template = `:) I am created dynamically`;
        const tmpCmp = Component({ template: template })(

            class MashupDynamicComponent implements OnInit {
                result: any[];
                constructor() { }

                ngOnInit() {

                }
            }

        );
        const tmpModule = NgModule(
            {
                declarations: [tmpCmp],
                imports: []
            })(class { });

        this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
            .then((factories) => {

                const f = factories.componentFactories[0];
                const cmpRef = f.create(this._injector, [], null, this._m);

                this.newCreatedComponent.insert(cmpRef.hostView);
            })

    }

}

我想知道如何将依赖项传递给动态创建的组件?就像我如何在新创建的组件中使用Http一样?

0 个答案:

没有答案