恢复动态生成的组件

时间:2018-09-01 02:29:24

标签: angular typescript

我有一个组件,可以接收一些数据,并动态生成其他一些组件(ngx图)。

  

这是指令

@Directive({
  selector: '[ad-host]',
})
export class PresentationDirective {
  constructor(public viewContainerRef: ViewContainerRef) {
  }
}
  

模板非常简单

<div class="presentation">
  <ng-template ad-host></ng-template>
</div>
  

在这里启动主要组件

presentations: Presentation[] = new Array();
components: any[] = new Array();

在初始化时,我会遍历数据数组并调用函数loadComponent

ngOnInit() {
  const temp = this.simulationResponse['presentations'];
  for (const presentation of temp) {
    this.presentations.push(presentation);
    this.loadComponent(this.getComponent(presentation['type']), 
    presentation['data']);
  }
}

此函数返回该组件,我添加此组件只是为了阐明问题。

getComponent(componentType: string) {
  switch (componentType) {
    case 'PIE': {
      return PieChartComponent;
    }
    case 'BAR': {
      return BarChartComponent;
    }
  }
}

每次调用时,Load Component都会创建一个组件,并设置该组件构建图形所需的数据

loadComponent(component: any, data: any) {
  const componentFactory = 
  this.componentFactoryResolver.resolveComponentFactory(component);
  const viewContainerRef = this.adHost.viewContainerRef;
  const componentRef = 
  viewContainerRef.createComponent(componentFactory);
  this.components.push(componentRef);
  (<AddData>componentRef.instance).single = data;
}

当数据更改时,我调用了另一个称为updatePresentations的函数

ngOnChanges() {
  this.updatePresentations();
}

但是在这里,在for的最后一行中,当我尝试分配数据时,出现两个错误

updatePresentations() {
  const viewContainerRef = this.adHost.viewContainerRef;
  for (let i = 0; i < viewContainerRef.length; i++) {
    const componentRef = viewContainerRef.get(i);
    const tmp = this.presentations[i];
    (<AddData>componentRef.instance).single = tmp['data'];
  }
}

第一个错误

  

src / app / simulator / presentation / presentation.component.ts(71,7)中的错误:>错误TS2322:类型“ {}”不能分配给类型“ any []”。

第二个错误

  

类型“ {}”中缺少属性“包含”。   src / app / simulator / presentation / presentation.component.ts(71,30):错误> TS2339:类型“ ViewRef”上不存在属性“ instance”。

我还不担心第一个杀害我,第二个杀了我,它说实例不是ViewRef的属性,但我是从存储它的地方获取该对象的并且在LoadComponent函数的最后一行中运行良好。

我很着急,看不到我所缺少的东西,任何帮助都将受到欢迎。

其他数据:

我主要基于角度指南的这一部分来构建 https://angular.io/guide/dynamic-component-loader

1 个答案:

答案 0 :(得分:0)

我对Angular并不熟悉,但正如@yurzui所暗示的那样,看来viewContainerRef.get(i)返回的是ViewRef而不是您想要的ComponentRef;请参阅documentation。为什么不使用this.components[i]呢?

相关问题