我已經適應您的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);
}
的問題似乎是,'this.appRef [ '_ rootComponents'] [0] .location'不會像預期的那樣返回「ViewContainerRef」。您能否將鏈接添加到包含指向類似示例鏈接的其他問題? –