问题
I'm trying to use the angular2 compiler to dynamically insert a component, which works fine as long as all code is in the default module.
But if try to put the component into it's own feature module, it breaks. The injected compiler instance (ModuleBoundCompiler) is bound to the default module not the feature one and I can't override the module in the compiler call, because I can't get a reference to it, due to circular dependencies (feature module exports component, component needs to reference feature module).
Any idea if this is a bug or am I doing something wrong?
Default Module:
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 { }
Feature Module:
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>) => {
// ...
});
}
}
来源:https://stackoverflow.com/questions/38898845/angular2-rc5-dynamically-compile-component-with-correct-module