动态加载自定义元素中的组件

时间:2016-06-01 16:08:22

标签: typescript angular

我试图在容器上注入一个组件

组件:

@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

因为containerElementRef类型变量,loadNextToLocation需要ViewContainerRef作为第二个参数。正如official docs所述,ViewContainerRef可以通过@ViewChild从元素中提取,但我还没有找到任何正确的例子。

使用Angular2.0.0rc1

1 个答案:

答案 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)
      });        
    }
}

另见Angular 2 dynamic tabs with user-click chosen components