我试图在容器上注入一个组件
组件:
@Component({...})
export class InvestmentProcess{
@ViewChild('container') container;
constructor(public dcl: DynamicComponentLoader) {}
loadComponent(fooComponent: Type){
this.dcl.loadNextToLocation(fooComponent, container);
}
}
模板:
<div #container> </div>
当我运行函数loadComponent
时,抛出以下错误:
TypeError: location.createComponent is not a function
因为container
是ElementRef
类型变量,loadNextToLocation
需要ViewContainerRef
作为第二个参数。正如official docs所述,ViewContainerRef
可以通过@ViewChild
从元素中提取,但我还没有找到任何正确的例子。
使用Angular2.0.0rc1
答案 0 :(得分:3)
DynamicComponentLoader
将被弃用。使用ViewContainerRef.createComponent()
@Component({...})
export class InvestmentProcess{
@ViewChild('container', {read: ViewContainerRef}) container:ViewContainerRef;
constructor(private resolver: ComponentResolver) {}
loadComponent(fooComponent: Type){
this.resolver.resolveComponent(fooComponent).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
});
}
}