2

I'm trying to use DynamicComponentLoader and the sample code is below:

import {Component, View, bootstrap,  OnInit, DynamicComponentLoader} from 'angular2';

...

DynamicComponentLoader.loadIntoLocation(PersonsComponent, itemElement);

When I run the app, I get the error:

DynamicComponentLoader.loadIntoLocation is not a function

How can I use DynamicComponentLoader.loadIntoLocation in ES6 JavaScript using class?

Oleksii Pavlenko
  • 1,327
  • 1
  • 11
  • 25
wonderful world
  • 10,969
  • 20
  • 97
  • 194
  • Did you inject it as it's shown in [documentation](https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html)? – Eric Martinez Oct 08 '15 at 12:43

2 Answers2

5

DynamicComponentLoader is class. It doesn't have any static method loadIntoLocation. But instances of this class have it. You must instantiate DynamicComponentLoader using dependency injection:

import { Component, View, DynamicComponentLoader, ElementRef } from 'angular2/angular2'

@Component({
  selector: 'dc'
})
@View({
  template: '<b>Some template</b>'
})
class DynamicComponent {}

@Component({
  selector: 'my-app'
})
@View({
  template: '<div #container></div>'
})
export class App {

  constructor(
    dynamicComponentLoader: DynamicComponentLoader, 
    elementRef: ElementRef
  ) {
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container');
  }
}

See this plunker

UPD

What about ES6, I've answered it here

Community
  • 1
  • 1
alexpods
  • 47,475
  • 10
  • 100
  • 94
  • Thank you. I don't use typescript but ES6 and Babel for transpiling. When I tried the code, I get the error 'NoAnnotationError {message: "Cannot resolve all parameters for ProductsComponen…ake sure they all have valid type or annotations.", stack: "Error: Cannot resolve all parameters for ProductsC…_view_factory.' – wonderful world Oct 09 '15 at 00:54
  • Do you have a sample for ES6? I don't know how to inject to ES6 classes. Thanks in advance. – wonderful world Oct 09 '15 at 00:56
0

DynamicComponentLoader is long gone.

https://angular.io/guide/dynamic-component-loader explains how it's done in newer Angular version.

  loadComponent() {
    this.currentAddIndex = (this.currentAddIndex + 1) % this.ads.length;
    let adItem = this.ads[this.currentAddIndex];

    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    let viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();

    let componentRef = viewContainerRef.createComponent(componentFactory);
    (<AdComponent>componentRef.instance).data = adItem.data;
  }
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567