2016-09-19 6 views
0

最近Angular2アプリを最終版にアップグレードしました。angular2 finalでコンポーネントを動的にロードしていますか?

私はオンラインで提供された多くの参考文献から実装しようとしましたが、成功しませんでした。 angular2 RC5で

、iは以下のようにコンパイラを使用して動的に私のコンポーネントをロードするために使用される:私はtoSetを使用してコンポーネントのインスタンス変数を設定

@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; 
    } 
} 

を。 しかし、angular2がリリースされたので、このメソッドは推奨されなくなりました。 と私はこれを角2の最終で行う方法についてはわかりません。

任意の入力?

ありがとうございます。

+3

これを確認してください(http://stackoverflow.com/q/38888008/ 1679310) –

答えて

0

私はこのようにそれをやっている:[?どうすれば角2.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:動的にロードされたcompenentをNgModuleのentryComponentsリストに追加します。 – dstr

関連する問題