我最近將我的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) –