[英]loading components dynamically in angular2 final?
I recently upgraded my angular2 app to final version. 我最近将angular2应用程序升级到最终版本。
I tried to implement from lot of references provided online but got no success. 我尝试从在线提供的大量参考文献中实现,但没有成功。
in angular2 RC5 , i used to load my components dynamically using compiler as below: 在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;
}
}
where I set instance variable for the component using toSet
. 我使用toSet
为组件设置实例变量。 but as angular2 has been released this method has been deprecated. 但是由于angular2已经发布,因此该方法已被弃用。 and I am not sure about how to get this done in angular2 final. 而且我不确定如何在angular2 final中完成这项工作。
any inputs? 任何输入?
thanks in advance. 提前致谢。
I am doing it like this: 我是这样做的:
System.import('path/to/MyComponent')
.then(fileContents => fileContents['MyComponent'])
.then(component => {
let factory = this.componentFactoryResolver.resolveComponentFactory(component);
this.container.createComponent(factory); //container: ViewContainerRef
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.