2016-09-19 87 views
0

我最近將我的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中完成這個任務。

任何輸入?

在此先感謝。

+3

檢查這個[?我如何使用/創建動態模板編譯動態組件與角2.0(http://stackoverflow.com/q/38888008/ 1679310) –

回答

0

我這樣做是這樣的:

System.import('path/to/MyComponent') 
      .then(fileContents => fileContents['MyComponent']) 
      .then(component => { 
       let factory = this.componentFactoryResolver.resolveComponentFactory(component); 
       this.container.createComponent(factory); //container: ViewContainerRef 
      }); 
+0

我目前得到這個錯誤:組件xxx不是任何NgModule的一部分,或者模塊沒有被導入到你的模塊中。有任何想法嗎??? – Gerardlamo

+0

@Gerardlamo:在NgModule的entryComponents列表中添加你的動態加載的元素。 – dstr