我正在尝试使用 DynamicComponentLoader ,示例代码如下:
import {Component, View, bootstrap, OnInit, DynamicComponentLoader} from 'angular2';
...
DynamicComponentLoader.loadIntoLocation(PersonsComponent, itemElement);
当我运行应用程序时,我收到错误:
DynamicComponentLoader.loadIntoLocation不是函数
如何使用类在ES6 JavaScript中使用DynamicComponentLoader.loadIntoLocation?
答案 0 :(得分: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
答案 1 :(得分:0)
DynamicComponentLoader
早已不复存在。
https://angular.io/guide/dynamic-component-loader解释了它是如何在较新的Angular版本中完成的。
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; }