我最近将我的angular2应用程序升级到最终版本。在angular2 final中动态加载组件?
我试图从很多在线提供的参考文献中实施,但没有取得成功。
在angular2 RC5,我使用动态使用如下编译器加载我的组件:
@Input('component-name') componentName: string;
@Input('component-model') componentModel: any;
@ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
private cmpRef: ComponentRef<any>;
public toSet: any;
keysRegister: string[] = [
'BASIC-CAROUSEL',
'BS-JUMBOTRON'
]
componentNames: string[]=[
"BasicCarouselComponent",
"BsJumbotronComponent"
]
constructor(private _compiler: Compiler, private _viewContainerRef:ViewContainerRef) { }
ngOnInit() {
this.toSet={
'componentModel':this.componentModel,
'componentInfo':this.componentInfo
};
}
ngAfterViewInit(): void {
let componentIndex = this.keysRegister.indexOf(this.componentName);
console.log(this.componentNames[componentIndex]);
if (this.cmpRef) {
this.cmpRef.destroy();
}
this._compiler.compileComponentAsync(StandardLib[this.componentNames[componentIndex]]).then(comp => {
let ref = this.target.createComponent(comp);
if (this.toSet) {
const keys = Object.keys(this.toSet);
keys.forEach(a => ref.instance[a] = this.toSet[a])
}
});
}
ngOnDestroy() {
if (this.cmpRef) {
this.cmpRef.destroy();
this.cmpRef = null;
}
}
其中I设置实例变量用于使用toSet
的组件。 但由于angular2已被释放,此方法已被弃用。 我不确定如何在angular2 final中完成这个任务。
任何输入?
在此先感谢。
检查这个[?我如何使用/创建动态模板编译动态组件与角2.0(http://stackoverflow.com/q/38888008/ 1679310) –