2016-12-21 93 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酷! – Katana24

+0

@ Katana24我有同樣的問題,你的解決方案几乎可以工作,但消息打印在根組件上,而不是在「spinner-message-container」中,你能給我一個想法嗎? –