angular2コンパイラを使用してコンポーネントを動的に挿入しようとしていますが、すべてのコードがデフォルト モジュールにある限り問題なく動作します。
しかし、コンポーネントを独自の機能モジュールに入れようとすると、壊れます。挿入されたコンパイラ インスタンス ( 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 { }
アプリ コンポーネント:
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>) => {
// ...
});
}
}