[英]loading components dynamically in angular2 final?
我最近將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中完成這項工作。
任何輸入?
提前致謝。
我是這樣做的:
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.