如何检查viewContainerRef Angular中是否已存在组件

时间:2018-02-23 13:44:02

标签: angular

我动态添加组件如下:

export class CustomersOverviewComponent implements OnInit, OnDestroy {

  @ViewChild(PanelDirective) customerHost: PanelDirective;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private sidebarService: SidebarService) {

  }

  ngOnDestroy(): void {

  }

  ngOnInit(): void {
    console.log('init');

    this.sidebarService.currentAddPanel.subscribe(panel => {
      if (panel instanceof PanelItem) {
        this.loadcomponent(panel);
      }
    });
  }

  loadcomponent(panel: PanelItem): void {
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(panel.component);
    let viewContainerRef = this.customerHost.viewContainerRef;

    console.log('viewcontainer', viewContainerRef);
    console.log('element', viewContainerRef.element);

    let componentRef = viewContainerRef.createComponent(componentFactory);

    (<IPanel>componentRef.instance).data = panel.data;
    (<IPanel>componentRef.instance).self = componentRef;
  }


}

但是在向viewContainer中添加一个新组件之前,我想循环它并检查我的组件是否已经存在。我怎么能这样做?

我无法在viewContainerRef中看到任何可循环的属性。

1 个答案:

答案 0 :(得分:0)

你不能简单地在本地分配吗?

loadcomponent(panel: PanelItem): void {
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(panel.component);
    let viewContainerRef = this.customerHost.viewContainerRef;

    if (!this.componentRef) {
        this.componentRef = viewContainerRef.createComponent(componentFactory);
    }

    (<IPanel>this.componentRef.instance).data = panel.data;
    (<IPanel>this.componentRef.instance).self = this.componentRef;

}