2017-10-26 1 views
2

ViewContainerRef를 사용하여 뷰에 구성 요소를 추가 할 수 있습니다. 예를 들어 클래스 이름을 참조로 사용하여 div 안에 구성 요소를 추가하십시오.

, HTML 파일 :

<div #Ref>it is possible to append the component here</div> 

TS 파일 :

@ViewChild("Ref", { read: ViewContainerRef }) 
public Ref: ViewContainerRef 

appendComponent() { 
    const factory = this.componentFactoryResolver.resolveComponentFactory(
    SingleframeComponent 
); 
    this.Ref.createComponent(factory); 
} 

하지만 내 경우에는 동적으로 클래스와 인덱스 심판을 사용하여 구성 요소를 추가 할 예를 들면

HTML 파일

<div #Ref> 
    <div class="appendComponentHere"></div> 
    <div class="appendComponentHere"> I need to append The component Here</div> 
    <div class="appendComponentHere"></div> 
</div> 

TS 그것은 쉽게해야

@ViewChild("Ref", { read: ViewContainerRef }) 
public Ref: ViewContainerRef 

appendComponent() { 
    const factory = this.componentFactoryResolver. 

    //something like this i need to do 

    this.Ref.element .nativeElement.getElementsByClassName("fullslidebody")[1].createComponent(factory); 
} 

답변

1

파일. 그냥 다음 사항을 확인하시기 바랍니다

const viewRef = this.Ref.createComponent(factory).hostView as EmbeddedViewRef<any>; 

const target = this.Ref.element.nativeElement.getElementsByClassName("fullslidebody")[1]; 
target.appendChild(viewRef.rootNodes[0]); 

Stackblitz Example

관련 문제