2017-11-05 17 views
0

コンポーネントの配列を動的にロードしようとしています。私は実行時にロードする必要があるすべてのコンポーネントを含む配列を持っています。配列のコードループに続いて、コンポーネントのファクトリを作成します。 `コンポーネントを動的にロードする角度2

gAfterViewInit() { 
     this.loadcomponents(); 
    } 
loadcomponents() { 
     for (let i = 0; i < this.components.length; i++) { 
      //this.sidetext[i] = this.components[i].sidetext; 
      //this.section_ttile[i] = this.components[i].section_ttile; 
      for (let j = 0; j < this.components[i].components.length; j++) { 
       let termItem = this.components[i].components[j]; 
       let componentFactory = this.componentFactoryResolver.resolveComponentFactory(termItem.component); 
       let viewContainerRef = this.termHost.viewContainerRef; 
       viewContainerRef.clear(); 
       let componentRef = viewContainerRef.createComponent(componentFactory); 
       (<TermComponent>componentRef.instance).data = termItem.data; 
      } 
     } 

` そして、ここに私のテンプレート

  <div class="div_for_ques" *ngFor="let component of components; let i=index"> 

       <div class="sec_two"> 
        <ng-template term-host></ng-template> 
       </div> 
      </div> 

あるしかし、問題は、動的にロードされたコンポーネントは、以前ロードされたコンポーネントのコンポーネントの一番上に表示されていることです。私はそれぞれのコンポーネントを別々のdivに配置したいと思っています。どのようにこれを達成するための任意の提案? 次は現在の出力です。

enter image description here

予想出力は、2つのそのような入力フィールドであるが、実際には完全に最初の重複のみ秒です。

+0

:このような

<div *ngFor="let v of views"> <div #target></div> </div> 

そして、あなたのコードになるインスタンスのコンポーネント。 – micronyks

+0

これをチェックアウトする[**媒体の投稿**](https://medium.com/@aravindfz/load-modal-component-dynamically-in-angular-5fda8e1dc3e7) – Aravind

+0

@micronyks質問を編集しました –

答えて

1

@ViewChildrenを使用する必要がありますので、コンテナのクエリリストを取得できます。

あなたのテンプレートは、このようなことができます:あなたは結果のDOMの画像を投稿することができれば、それは参考になる

@ViewChildren('target', {read: ViewContainerRef}) container: QueryList<ViewContainerRef>; 

ngAfterViewInit(){ 
    this.container.toArray().map((viewContainerRef, i) => { 
    let componentFactory = this.resolver.resolveComponentFactory(this.components[i]); // actually that should be this.components[i].components[j] something in your case 
    let componentRef = viewContainerRef.createComponent(componentFactory); 
    }); 
} 
関連する問題