【发布时间】:2016-09-19 10:01:41
【问题描述】:
我最近将我的 angular2 应用升级到了最终版本。
我尝试从网上提供的大量参考资料中实现,但没有成功。
在 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;
}
}
我使用 toSet 为组件设置实例变量。
但随着 angular2 的发布,这种方法已被弃用。
而且我不确定如何在 angular2 final 中完成这项工作。
任何输入?
提前致谢。
【问题讨论】:
标签: angular typescript