Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elementRef.createComponent is not a function

Tags:

angular

I am trying to load a spinner component dynamically on click of a button.

Plunker link is here,

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

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

    return this.startInside(elementRef, null);

I am getting below error:

elementRef.createComponent is not a function.

Please suggest!

like image 427
shazia perween Avatar asked Sep 05 '25 04:09

shazia perween


1 Answers

I've adapted your plunkr and forked it to here but in summary you should do this:

Add a placeholder to the template, then assign it as a @ViewChild and pass that to the service. Here's the app.ts now:

@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);
  }
}

And finally in the service you can just do this:

 public start(placeholder) {
        let elementRef = placeholder;
        return this.startInside(elementRef, null);
    }
like image 144
Katana24 Avatar answered Sep 07 '25 21:09

Katana24