我正在尝试实施动态组件,如http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/
中所述我对在Angular2的每个后续版本中无用的解决方案感到困惑。我已经尝试http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2-rc-5/只是发现它没有编译,然后最后invoke pipe during run time using pipe name /metadata仍然没有做出原始想法的简单事情:我给了HTML或URL作为动态编译组件的参数。
这就是我实际拥有的:
import {
Component, Input, ViewContainerRef, ReflectiveInjector,
ViewChild, OnInit, Compiler, NgModule
} from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
@Component({
selector: 'my-dynamic',
template: `
<div class="my-dynamic">
<div #content></div>
</div>
`
})
export class MyDynamic implements OnInit {
@Input('src') src: string;
@ViewChild('content') content;
constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {
}
ngOnInit() {
const src = this.src
@Component({
selector: 'dynamic-comp',
templateUrl: src
})
class DynamicComponent {
};
@NgModule({
imports: [BrowserModule],
declarations: [DynamicComponent]
})
class DynamicModule {}
this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
.then(({moduleFactory, componentFactories}) => {
const compFactory = componentFactories.find(x => x.componentType === DynamicComponent);
const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
const cmpRef = this.vcRef.createComponent(compFactory, 0, injector, []);
});
}
}
以及如何调用它:
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<my-dynamic [src]="templateSource"></my-dynamic>
`
})
export class AppComponent implements OnInit, AfterViewInit {
title: string = "Angular Sandbox";
templateSource: string = "/templates/dynamic/dynamic1.htm"
}
设置&#39;模板&#39;作为任意字符串工作,但使用templateUrl,模板将被加载,但不会显示。控制台上没有错误...
是否可以使用任意模板网址创建动态组件?或者它不会那样工作?