Angular2 RC5使用正确的模块动态编译组件

时间:2016-08-11 14:14:00

标签: angular angular2-compiler

我尝试使用angular2 compiler动态插入一个组件,只要所有代码都在默认模块中,就可以正常工作。

但是如果尝试将组件放入其自己的功能模块中,它就会中断。 注入的编译器实例(ModuleBoundCompiler)绑定到默认模块而不是特性模块,我无法覆盖编译器调用中的模块,因为我无法获得对它的引用,到期循环依赖(特征模块导出组件,组件需要引用特征模块)。

知道这是一个错误还是我做错了?

默认模块:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppComponent} from './app.component';

@NgModule({
    imports: [BrowserModule, FeatureModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

AppComponent:

import {Component} from "@angular/core";

@Component({
    selector: "my-app",
    template: `
        <h1>Angular2 RC5 Test</h1>
        <feature-component></feature-component>
    `
})
export class AppComponent { }

功能模块

import { NgModule }     from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule }  from "@angular/forms";

import { FeatureComponent }  from "./feature.component";
import { FeatureService }    from "./feature.service";


@NgModule({
    imports: [CommonModule, FormsModule],
    declarations: [FeatureComponent],
    exports: [FeatureComponent],
    providers: [FeatureService]
})
export class FeatureModule { }

FeatureComponent

import {Component, Compiler, ComponentFactory} from "@angular/core";

import {FeatureService} from "./feature.service";

// import {FeatureModule} from "./feature.module"; // produces error if referenced due to circular dependency


@Component({
    selector: "feature-component",
    template: "<div>Feature Component</div>"
})
export class FeatureComponent {

    constructor(private _service: FeatureService, private _compiler: Compiler) {
        // compiler currently belongs to AppModule (should be FeatureModule)
        console.log((<any>this._compiler)._ngModule); // outputs function AppModule() { }
    }

    public createComponent(component: any): void {
        this._compiler.compileComponentAsync(component /* , could override module here, but can't get reference */)
            .then((factory: ComponentFactory<any>) => {
                 // ...
            });
    }
}

0 个答案:

没有答案