2017-11-05 10 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

예상 출력은 두 개의 같은 입력 필드이지만 실제로 완전히 처음 중첩 만 초이다.

+0

당신이 결과 DOM의 이미지를 게시 할 수 있다면 도움이 될 것입니다. – micronyks

+0

체크 아웃 [** 중간 게시물 **] (https://medium.com/@aravindfz/load-modal-component-dynamically-in-angular-5fda8e1dc3e7) – Aravind

+0

@micronyks 질문을 편집했습니다 –

답변

1

@ViewChildren을 사용해야 컨테이너의 쿼리 목록을 얻을 수 있습니다.

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

그리고 코드 것 같은 인스턴스 구성 요소 :

템플릿이 이렇게 될 수

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