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?

1
  • Did you inject it as it's shown in documentation? Commented Oct 8, 2015 at 12:43

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.'
Do you have a sample for ES6? I don't know how to inject to ES6 classes. Thanks in advance.
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;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.