我试图在单击按钮时动态加载旋转器组件。
plunker链接在这里,
http://plnkr.co/edit/ueeqqrzx7rikso49rchu?p=preview
let elementRef: ElementRef = this.appRef['_rootComponents'][0].location;
return this.startInside(elementRef, null);
我要低于错误:
ElementRef.CreateComponent不是函数。
请建议!
我已经调整了您的plunkr并将其分配给这里,但总而言之,您应该这样做:
将一个占位符添加到模板中,然后将其分配为@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);
}