2015-10-08 2 views
2

Я пытаюсь использовать DynamicComponentLoader и пример кода ниже:DynamicComponentLoader.loadIntoLocation не является функцией ошибки в Angular2

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

... 

DynamicComponentLoader.loadIntoLocation(PersonsComponent, itemElement); 

Когда я запустить приложение, я получаю ошибку:

DynamicComponentLoader.loadIntoLocation is not a function

Как я могу использовать DynamicComponentLoader.loadIntoLocation в ES6 JavaScript с использованием класса?

+0

ли вы вводить его, как это показано в [документации] (https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html)? –

ответ

5

DynamicComponentLoader является класс. Он не имеет статического метода loadIntoLocation. Но экземпляры этого класса есть. Вы должны создать экземпляр DynamicComponentLoader с помощью инъекции зависимостей:

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

См this plunker

UPD

насчет ES6, я ответил here

+0

Спасибо. Я не использую машинопись, но ES6 и Babel для пересылки. Когда я попробовал код, я получаю сообщение об ошибке «NoAnnotationError {message:« Не удается разрешить все параметры для ProductComponen ... ake уверен, что все они имеют допустимый тип или аннотации. », Стек:« Ошибка: не удается разрешить все параметры для ProductsC ... _view_factory ». –

+0

У вас есть образец для ES6? Я не знаю, как вводить классы ES6. Спасибо заранее. –

+0

@wonderfulworld Я обновил ответ – alexpods

0

DynamicComponentLoader давно прошло.

https://angular.io/guide/dynamic-component-loader объясняет, как это делается в новой Угловой версии.

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; 
    } 
Смежные вопросы