2016-12-21 1 views
1

버튼을 클릭 할 때 스피너 구성 요소를 동적으로로드하려고합니다.elementRef.createComponent가 함수가 아닙니다

Plunker 링크는 여기에 내가 오류가 아래 얻고있다

http://plnkr.co/edit/UEEQQRzX7RIkSO49rCHu?p=preview

let elementRef: ElementRef = this.appRef['_rootComponents'][0].location; 

    return this.startInside(elementRef, null); 

입니다 :

elementRef.createComponent is not a function.

제안하십시오!

+0

문제점하는 것 같다 'this.appRef ['_ rootComponents '] [0] .location' 예상대로'ViewContainerRef'를 반환하지 않습니다. 비슷한 예제에 대한 링크가 포함 된 다른 질문에 대한 링크를 추가 할 수 있습니까? –

답변

2

나는 당신의 plunkr 적응하고 here에 갈래하지만 요약이 작업을 수행해야했습니다

다음, 템플릿에 자리 표시 자 추가 @ViewChild으로 지정하고 서비스에 그것을 전달합니다. 여기에 지금 app.ts입니다 :

@Component({ 
    selector: 'my-app', 
    providers: [SpinnerService], 
    template: ` 
    <div> 
     <button type="button" (click)="showSpinner()">Show Spinner</button> 
     <div #spinner></div> 
    </div> 
    ` 
}) 
export class App { 
    @ViewChild('spinner', { read: ViewContainerRef }) container: ViewContainerRef;  

    constructor(private _spinner: SpinnerService) {} 

    showSpinner() { 
    this._spinner.start(this.container); 
    setTimeout(() => this._spinner.stop(), 5000); 
    } 
} 

그리고 마지막으로 서비스에 방금이 수행 할 수

public start(placeholder) { 
     let elementRef = placeholder; 
     return this.startInside(elementRef, null); 
    } 
+0

와우! 감사합니다, 완벽하게 작동합니다! –

+0

@shaziaperween cool! – Katana24

+0

@ Katana24 나는 똑같은 문제가 있었고 당신의 솔루션은 거의 효과가 있었지만 메시지는'spinner-message-container'가 아닌 루트 구성 요소에 인쇄되었습니다. 아이디어를 줄 수 있습니까? –

관련 문제